#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import COOPGIS_FormMisc

from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import django
import os
import datetime
import djangoproject.settings
from django.contrib.auth.models import User

#NearbyRoads=Road.objects.filter(Line__distance_lte=(self.Point, 9000 * djangoproject.settings.COOPGISDistanceMultiplier))

def GetNumberOfConditionsListedOnForm(point=None):
    if(point):
        return 1 + Condition.objects.filter(Point__distance_lte=(point, 1)).count()
    else:
        return 1

def GetNumberOfOutdoorLightsListedOnForm(point=None, meternumber=None):
    OutdoorLights = Condition.objects.filter(PriorityOutdoorLightingConversionIndicator=True).exclude(
                                             DeletedIndicator=True).exclude(ArchivedIndicator=True)
    if meternumber:
        return OutdoorLights.filter(OutdoorLightMeterNumber=meternumber).count() + 1
    if point:
        return OutdoorLights.filter(Point__distance_lte=(point, 1)).count() + 1
    return 1
   
def BuildConditionEditorForm(DefaultMap, point=None):
    NumberOfConditionsListedOnForm=GetNumberOfConditionsListedOnForm(point=point)
    Dict={}
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([DefaultMap.id, str(DefaultMap.Name)[:30]])
    Maps=Map.objects.all().order_by('Name')
    for i in Maps:
        if(not i == DefaultMap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    #Build ConditionDepartment Choices List
    ConditionDepartmentChoices=[]
    ConditionDepartments=ConditionDepartment.objects.all().order_by('id')
    for i in ConditionDepartments:
        ConditionDepartmentChoices.append([i.id, str(i.Name)])
    #General Fields for selecting the map and running queries
    ConditionStatusChoices=[]
    ConditionStatuses=ConditionStatus.objects.all().order_by('Name')
    for i in ConditionStatuses:
        ConditionStatusChoices.append([i.id, str(i)])
    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    Dict['SelectMapNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SelectRoadName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SelectStationTagNumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'6'}))
    Dict['SelectStationid']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'6'}))
    Dict['SelectMeterNumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SelectDCSINumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SelectGPSIndicator']=forms.BooleanField()
    Dict['StationComment']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['UpdateStationCommentIndicator']=forms.BooleanField(required=False)
    for i in range(0, NumberOfConditionsListedOnForm):
        Dict['UpdateIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['Conditionid' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['ConditionDepartment' + str(i)]=forms.ChoiceField(ConditionDepartmentChoices, required=False)
        Dict['PriorityImmediateIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['PriorityASAPIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['PriorityRoutineIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['PriorityEverythingFixedMaintenanceOnlyIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['PriorityEverythingOkInspectionOnlyIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['PriorityVegetationNeedsAttentionIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['PoleConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['GuyAnchorConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['InsulatorConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['ConductorConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['RightOfWayConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['PadMountConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['VaultConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['RiserCableConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['PersonReporting' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
        Dict['DateTimeReported' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['ReceivedByOperationsIndicator' + str(i)] = forms.BooleanField(required=False) 
        Dict['DateTimeReceivedByOperations' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['StationIdentifier' + str(i)]=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
        Dict['TagNumber' + str(i)]=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['Description' + str(i)]=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3, 'cols':40}))
        Dict['WorkOrderNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['WorkRemarks' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
        Dict['WorkPerformedBy' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['WorkHours' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['WorkDate' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['WorkCompletedIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['WorkNotCompletedIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['WorkNotCompletedDescription' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
        Dict['WorkForeman' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['WorkForemanSignoffIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['WorkForemanSignoffDateTime' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['ReviewIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['ReviewAdditionalAttentionNeededIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['ReviewComments' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
        Dict['ReviewUserName' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['ReviewDateTime' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['DeletedIndicator'+ str(i)]=forms.BooleanField(required=False)
        Dict['ArchivedUserName' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['ArchivedDateTime' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['ArchivedIndicator'+ str(i)]=forms.BooleanField(required=False)
        Dict['CreateDateTime'+ str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6', 'READONLY':'True'}))
        Dict['CreateUserName'+ str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6', 'READONLY':'True'}))
        Dict['LastModifyDateTime'+ str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6', 'READONLY':'True'}))
        Dict['LastModifyUserName'+ str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6', 'READONLY':'True'}))
    return Dict


def ProcessConditionEditorFormEntry(form, ConditionNumber, SelectionStation, UserName, ApplicationName):
    """Processes the ConditionEditor Form to create new Hazard Condition Reports or Edit exiting Ones."""
    if(not SelectionStation):
        return #Changes cannot be made to Condition Reports if there is not a current station at the report site
    ConditionNumber=str(ConditionNumber)
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator' + ConditionNumber)
    Conditionid=COOPGIS_FormMisc.FormGetString(form, 'Conditionid' + ConditionNumber, 'New')
    ConditionDepartmentid=COOPGIS_FormMisc.FormGetInteger(form, 'ConditionDepartment' + ConditionNumber)
    PriorityImmediateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PriorityImmediateIndicator' + ConditionNumber)
    PriorityASAPIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PriorityASAPIndicator' + ConditionNumber)
    PriorityRoutineIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PriorityRoutineIndicator' + ConditionNumber)
    PriorityEverythingFixedMaintenanceOnlyIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PriorityEverythingFixedMaintenanceOnlyIndicator' + ConditionNumber)
    PriorityEverythingOkInspectionOnlyIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PriorityEverythingOkInspectionOnlyIndicator' + ConditionNumber)
    PriorityVegetationNeedsAttentionIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PriorityVegetationNeedsAttentionIndicator' + ConditionNumber) 
    PoleConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'PoleConditionStatus' + ConditionNumber)
    GuyAnchorConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'GuyAnchorConditionStatus' + ConditionNumber)
    InsulatorConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'InsulatorConditionStatus' + ConditionNumber)
    ConductorConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'ConductorConditionStatus' + ConditionNumber)
    RightOfWayConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'RightOfWayConditionStatus' + ConditionNumber)
    PadMountConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'PadMountConditionStatus' + ConditionNumber)
    VaultConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'VaultConditionStatus' + ConditionNumber)
    RiserCableConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'RiserCableConditionStatus' + ConditionNumber)
    PersonReporting=COOPGIS_FormMisc.FormGetString(form, 'PersonReporting' + ConditionNumber)
    DateTimeReported=COOPGIS_FormMisc.FormGetDateTime(form, 'DateTimeReported' + ConditionNumber)
    ReceivedByOperationsIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ReceivedByOperationsIndicator' + ConditionNumber)
    DateTimeReceivedByOperations=COOPGIS_FormMisc.FormGetDateTime(form, 'DateTimeReceivedByOperations' + ConditionNumber)
    StationIdentifier=COOPGIS_FormMisc.FormGetString(form, 'StationIdentifier' + ConditionNumber)
    TagNumber=COOPGIS_FormMisc.FormGetString(form, 'TagNumber' + ConditionNumber)
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description' + ConditionNumber)
    WorkOrderNumber=COOPGIS_FormMisc.FormGetString(form, 'WorkOrderNumber' + ConditionNumber)
    WorkRemarks=COOPGIS_FormMisc.FormGetString(form, 'WorkRemarks' + ConditionNumber)
    WorkPerformedBy=COOPGIS_FormMisc.FormGetString(form, 'WorkPerformedBy' + ConditionNumber)
    WorkHours=COOPGIS_FormMisc.FormGetFloat(form, 'WorkHours' + ConditionNumber)
    WorkDate=COOPGIS_FormMisc.FormGetDateTime(form, 'WorkDate' + ConditionNumber)
    WorkCompletedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'WorkCompletedIndicator' + ConditionNumber)
    WorkNotCompletedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'WorkNotCompletedIndicator' + ConditionNumber)
    WorkNotCompletedDescription=COOPGIS_FormMisc.FormGetString(form, 'WorkNotCompletedDescription' + ConditionNumber)
    WorkForeman=COOPGIS_FormMisc.FormGetString(form, 'WorkForeman' + ConditionNumber)
    WorkForemanSignoffIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'WorkForemanSignoffIndicator' + ConditionNumber)
    WorkForemanSignoffDateTime=COOPGIS_FormMisc.FormGetDateTime(form, 'WorkForemanSignoffDateTime' + ConditionNumber)
    ReviewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ReviewIndicator' + ConditionNumber)
    ReviewAdditionalAttentionNeededIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ReviewAdditionalAttentionNeededIndicator' + ConditionNumber)
    ReviewComments=COOPGIS_FormMisc.FormGetString(form, 'ReviewComments' + ConditionNumber)
    ReviewUserName=COOPGIS_FormMisc.FormGetString(form, 'ReviewUserName' + ConditionNumber)
    ReviewDateTime=COOPGIS_FormMisc.FormGetDateTime(form, 'ReviewDateTime' + ConditionNumber)

    ArchivedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ArchivedIndicator' + ConditionNumber)
    ArchivedUserName=COOPGIS_FormMisc.FormGetString(form, 'ArchivedUserName' + ConditionNumber)
    ArchivedDateTime=COOPGIS_FormMisc.FormGetDateTime(form, 'ArchivedDateTime' + ConditionNumber)

    DeletedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeletedIndicator' + ConditionNumber)
    LastModifyDateTime, LastModifyUserName=CalculateConditionCreateData(UserName, Conditionid)
    point, StationIdentifier = CalculateConditionPoint(Conditionid, StationIdentifier, TagNumber, SelectionStation)
    if(UpdateIndicator and ApplicationName == djangoproject.settings.COOPGISConditionEditorApplicationName):
        if(Conditionid == 'New' or not Conditionid):   
            command=Command()
            command=command.Create(Name='CreateCondition', PriorityImmediateIndicator=PriorityImmediateIndicator,
                                   PriorityASAPIndicator=PriorityASAPIndicator, PriorityRoutineIndicator=PriorityRoutineIndicator,
                                   PriorityEverythingFixedMaintenanceOnlyIndicator=PriorityEverythingFixedMaintenanceOnlyIndicator,
                                   PriorityEverythingOkInspectionOnlyIndicator=PriorityEverythingOkInspectionOnlyIndicator,
                                   PriorityVegetationNeedsAttentionIndicator=PriorityVegetationNeedsAttentionIndicator,
                                   PriorityOutdoorLightingConversionIndicator=False, 
                                   PersonReporting=PersonReporting, DateTimeReported=DateTimeReported, 
                                   ReceivedByOperationsIndicator=ReceivedByOperationsIndicator, 
                                   DateTimeReceivedByOperations=DateTimeReceivedByOperations, 
                                   StationIdentifier=StationIdentifier, TagNumber=TagNumber, Point=point,
                                   Description=Description, WorkOrderNumber=WorkOrderNumber, WorkRemarks=WorkRemarks,
                                   WorkPerformedBy=WorkPerformedBy, HoursWorkedQuantity=WorkHours, WorkDate=WorkDate, 
                                   WorkCompletedIndicator=WorkCompletedIndicator, 
                                   WorkNotCompletedIndicator=WorkNotCompletedIndicator,
                                   WorkNotCompletedDescription=WorkNotCompletedDescription, WorkForeman=WorkForeman,
                                   WorkForemanSignoffIndicator=WorkForemanSignoffIndicator, 
                                   WorkForemanSignoffDateTime=WorkForemanSignoffDateTime,
                                   ReviewIndicator=ReviewIndicator, 
                                   ReviewAdditionalAttentionNeededIndicator=ReviewAdditionalAttentionNeededIndicator,
                                   ReviewComments=ReviewComments, ReviewUserName=ReviewUserName, ReviewDateTime=ReviewDateTime,
                                   DeletedIndicator=DeletedIndicator, CommandUserName=UserName,
                                   LastModifyDateTime=LastModifyDateTime, LastModifyUserName=LastModifyUserName,
                                   ArchivedIndicator=ArchivedIndicator, ArchivedUserName=ArchivedUserName, 
                                   ArchivedDateTime=ArchivedDateTime, ConditionDepartmentid=ConditionDepartmentid,
                                   PoleConditionStatus=PoleConditionStatus, GuyAnchorConditionStatus=GuyAnchorConditionStatus,
                                   InsulatorConditionStatus=InsulatorConditionStatus, ConductorConditionStatus=ConductorConditionStatus,
                                   RightOfWayConditionStatus=RightOfWayConditionStatus, PadMountConditionStatus=PadMountConditionStatus,
                                   VaultConditionStatus=VaultConditionStatus, RiserCableConditionStatus=RiserCableConditionStatus)
            condition=command.Process()
        elif(Conditionid):  
            ConditionToEdit=Condition.objects.filter(id=Conditionid)[0]
            Objectid, ObjectIndexWhenReverseSorted=ConditionToEdit.GetCommandidData()
            command=Command()
            command=command.Create(Name='EditCondition', PriorityImmediateIndicator=PriorityImmediateIndicator,
                                   PriorityASAPIndicator=PriorityASAPIndicator, PriorityRoutineIndicator=PriorityRoutineIndicator,
                                   PriorityEverythingFixedMaintenanceOnlyIndicator=PriorityEverythingFixedMaintenanceOnlyIndicator,
                                   PriorityEverythingOkInspectionOnlyIndicator=PriorityEverythingOkInspectionOnlyIndicator,
                                   PriorityVegetationNeedsAttentionIndicator=PriorityVegetationNeedsAttentionIndicator,
                                   PriorityOutdoorLightingConversionIndicator=False,
                                   PersonReporting=PersonReporting, DateTimeReported=DateTimeReported, 
                                   ReceivedByOperationsIndicator=ReceivedByOperationsIndicator, 
                                   DateTimeReceivedByOperations=DateTimeReceivedByOperations, 
                                   StationIdentifier=StationIdentifier, TagNumber=TagNumber, StartPoint=point,
                                   Description=Description, WorkOrderNumber=WorkOrderNumber, WorkRemarks=WorkRemarks,
                                   WorkPerformedBy=WorkPerformedBy, HoursWorkedQuantity=WorkHours, WorkDate=WorkDate, 
                                   WorkCompletedIndicator=WorkCompletedIndicator, 
                                   WorkNotCompletedIndicator=WorkNotCompletedIndicator,
                                   WorkNotCompletedDescription=WorkNotCompletedDescription, WorkForeman=WorkForeman,
                                   WorkForemanSignoffIndicator=WorkForemanSignoffIndicator, 
                                   WorkForemanSignoffDateTime=WorkForemanSignoffDateTime,
                                   ReviewIndicator=ReviewIndicator, 
                                   ReviewAdditionalAttentionNeededIndicator=ReviewAdditionalAttentionNeededIndicator,
                                   ReviewComments=ReviewComments, ReviewUserName=ReviewUserName, ReviewDateTime=ReviewDateTime,
                                   DeletedIndicator=DeletedIndicator, CommandUserName=UserName,
                                   LastModifyDateTime=LastModifyDateTime, LastModifyUserName=LastModifyUserName,
                                   ArchivedIndicator=ArchivedIndicator, ArchivedUserName=ArchivedUserName, 
                                   ArchivedDateTime=ArchivedDateTime, Objectid=Objectid, 
                                   ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted, ConditionDepartmentid=ConditionDepartmentid,
                                   PoleConditionStatus=PoleConditionStatus, GuyAnchorConditionStatus=GuyAnchorConditionStatus,
                                   InsulatorConditionStatus=InsulatorConditionStatus, ConductorConditionStatus=ConductorConditionStatus,
                                   RightOfWayConditionStatus=RightOfWayConditionStatus, PadMountConditionStatus=PadMountConditionStatus,
                                   VaultConditionStatus=VaultConditionStatus, RiserCableConditionStatus=RiserCableConditionStatus)
            command.Process()
    elif(UpdateIndicator and ApplicationName == djangoproject.settings.COOPGISConditionCreateApplicationName):
        if(Conditionid == 'New' or not Conditionid):   
            command=Command()
            command=command.Create(Name='CreateCondition', PriorityImmediateIndicator=PriorityImmediateIndicator,
                                   PriorityASAPIndicator=PriorityASAPIndicator, PriorityRoutineIndicator=PriorityRoutineIndicator,
                                   PriorityEverythingFixedMaintenanceOnlyIndicator=PriorityEverythingFixedMaintenanceOnlyIndicator,
                                   PriorityEverythingOkInspectionOnlyIndicator=PriorityEverythingOkInspectionOnlyIndicator,
                                   PriorityVegetationNeedsAttentionIndicator=PriorityVegetationNeedsAttentionIndicator,
                                   PriorityOutdoorLightingConversionIndicator=False,
                                   PersonReporting=PersonReporting, DateTimeReported=DateTimeReported, 
                                   ReceivedByOperationsIndicator=ReceivedByOperationsIndicator, 
                                   DateTimeReceivedByOperations=DateTimeReceivedByOperations, 
                                   StationIdentifier=StationIdentifier, TagNumber=TagNumber, StartPoint=point,
                                   Description=Description, WorkOrderNumber='', WorkRemarks='',
                                   WorkPerformedBy='', HoursWorkedQuantity=0, WorkDate=None, 
                                   WorkCompletedIndicator=False, 
                                   WorkNotCompletedIndicator=False,
                                   WorkNotCompletedDescription='', WorkForeman='',
                                   WorkForemanSignoffIndicator=False, 
                                   WorkForemanSignoffDateTime=None,
                                   ReviewIndicator=False, 
                                   ReviewAdditionalAttentionNeededIndicator=False,
                                   ReviewComments='', ReviewUserName='', ReviewDateTime=None,
                                   DeletedIndicator=False, CommandUserName=UserName,
                                   LastModifyDateTime=None, LastModifyUserName='',
                                   ArchivedIndicator=False, ArchivedUserName='', 
                                   ArchivedDateTime=None, ConditionDepartmentid=ConditionDepartmentid,
                                   PoleConditionStatus=PoleConditionStatus, GuyAnchorConditionStatus=GuyAnchorConditionStatus,
                                   InsulatorConditionStatus=InsulatorConditionStatus, ConductorConditionStatus=ConductorConditionStatus,
                                   RightOfWayConditionStatus=RightOfWayConditionStatus, PadMountConditionStatus=PadMountConditionStatus,
                                   VaultConditionStatus=VaultConditionStatus, RiserCableConditionStatus=RiserCableConditionStatus)
            condition=command.Process()
        elif(Conditionid):  
            ConditionToEdit=Condition.objects.filter(id=Conditionid)[0]
            Objectid, ObjectIndexWhenReverseSorted=ConditionToEdit.GetCommandidData()
            command=Command()
            command=command.Create(Name='EditCondition', PriorityImmediateIndicator=PriorityImmediateIndicator,
                                   PriorityASAPIndicator=PriorityASAPIndicator, PriorityRoutineIndicator=PriorityRoutineIndicator,
                                   PriorityEverythingFixedMaintenanceOnlyIndicator=PriorityEverythingFixedMaintenanceOnlyIndicator,
                                   PriorityEverythingOkInspectionOnlyIndicator=PriorityEverythingOkInspectionOnlyIndicator,
                                   PriorityVegetationNeedsAttentionIndicator=PriorityVegetationNeedsAttentionIndicator,
                                   PriorityOutdoorLightingConversionIndicator=False,
                                   PersonReporting=PersonReporting, DateTimeReported=DateTimeReported, 
                                   ReceivedByOperationsIndicator=ReceivedByOperationsIndicator, 
                                   DateTimeReceivedByOperations=DateTimeReceivedByOperations, 
                                   StationIdentifier=StationIdentifier, TagNumber=TagNumber, StartPoint=point,
                                   Description=Description, WorkOrderNumber=ConditionToEdit.WorkOrderNumber,
                                   WorkRemarks=ConditionToEdit.WorkRemarks,
                                   WorkPerformedBy=ConditionToEdit.WorkPerformedBy, 
                                   HoursWorkedQuantity=ConditionToEdit.WorkHours, WorkDate=ConditionToEdit.WorkDate, 
                                   WorkCompletedIndicator=ConditionToEdit.WorkCompletedIndicator, 
                                   WorkNotCompletedIndicator=ConditionToEdit.WorkNotCompletedIndicator,
                                   WorkNotCompletedDescription=ConditionToEdit.WorkNotCompletedDescription, 
                                   WorkForeman=ConditionToEdit.WorkForeman,
                                   WorkForemanSignoffIndicator=ConditionToEdit.WorkForemanSignoffIndicator, 
                                   WorkForemanSignoffDateTime=ConditionToEdit.WorkForemanSignoffDateTime,
                                   ReviewIndicator=ConditionToEdit.ReviewIndicator, 
                                   ReviewAdditionalAttentionNeededIndicator=ConditionToEdit.ReviewAdditionalAttentionNeededIndicator,
                                   ReviewComments=ConditionToEdit.ReviewComments, 
                                   ReviewUserName=ConditionToEdit.ReviewUserName, 
                                   ReviewDateTime=ConditionToEdit.ReviewDateTime,
                                   DeletedIndicator=ConditionToEdit.DeletedIndicator, 
                                   CommandUserName=UserName,
                                   LastModifyDateTime=ConditionToEdit.LastModifyDateTime, 
                                   LastModifyUserName=ConditionToEdit.LastModifyUserName,
                                   ArchivedIndicator=ConditionToEdit.ArchivedIndicator, 
                                   ArchivedUserName=ConditionToEdit.ArchivedUserName, 
                                   ArchivedDateTime=ConditionToEdit.ArchivedDateTime, Objectid=Objectid, 
                                   ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                                   ConditionDepartmentid=ConditionDepartmentid,
                                   PoleConditionStatus=PoleConditionStatus, GuyAnchorConditionStatus=GuyAnchorConditionStatus,
                                   InsulatorConditionStatus=InsulatorConditionStatus, ConductorConditionStatus=ConductorConditionStatus,
                                   RightOfWayConditionStatus=RightOfWayConditionStatus, PadMountConditionStatus=PadMountConditionStatus,
                                   VaultConditionStatus=VaultConditionStatus, RiserCableConditionStatus=RiserCableConditionStatus)
            command.Process()
    elif(UpdateIndicator and ApplicationName == djangoproject.settings.COOPGISConditionWorkApplicationName):
        if(Conditionid):  
            ConditionToEdit=Condition.objects.filter(id=Conditionid)[0]
            Objectid, ObjectIndexWhenReverseSorted=ConditionToEdit.GetCommandidData()
            command=Command()
            command=command.Create(Name='EditCondition', PriorityImmediateIndicator=ConditionToEdit.PriorityImmediateIndicator,
                                   PriorityASAPIndicator=ConditionToEdit.PriorityASAPIndicator, 
                                   PriorityRoutineIndicator=ConditionToEdit.PriorityRoutineIndicator,
                                   PriorityEverythingFixedMaintenanceOnlyIndicator=ConditionToEdit.PriorityEverythingFixedMaintenanceOnlyIndicator,
                                   PriorityEverythingOkInspectionOnlyIndicator=ConditionToEdit.PriorityEverythingOkInspectionOnlyIndicator,
                                   PriorityVegetationNeedsAttentionIndicator=ConditionToEdit.PriorityVegetationNeedsAttentionIndicator,
                                   PriorityOutdoorLightingConversionIndicator=False,
                                   PersonReporting=ConditionToEdit.PersonReporting, DateTimeReported=ConditionToEdit.DateTimeReported, 
                                   ReceivedByOperationsIndicator=ConditionToEdit.ReceivedByOperationsIndicator, 
                                   DateTimeReceivedByOperations=ConditionToEdit.DateTimeReceivedByOperations,  
                                   StationIdentifier=ConditionToEdit.StationIdentifier, TagNumber=ConditionToEdit.TagNumber, 
                                   StartPoint=ConditionToEdit.Point,
                                   Description=ConditionToEdit.Description, WorkOrderNumber=WorkOrderNumber,
                                   WorkRemarks=WorkRemarks,
                                   WorkPerformedBy=WorkPerformedBy, 
                                   HoursWorkedQuantity=WorkHours, WorkDate=WorkDate, 
                                   WorkCompletedIndicator=WorkCompletedIndicator, 
                                   WorkNotCompletedIndicator=WorkNotCompletedIndicator,
                                   WorkNotCompletedDescription=WorkNotCompletedDescription, 
                                   WorkForeman=WorkForeman,
                                   WorkForemanSignoffIndicator=WorkForemanSignoffIndicator, 
                                   WorkForemanSignoffDateTime=WorkForemanSignoffDateTime,
                                   ReviewIndicator=ConditionToEdit.ReviewIndicator, 
                                   ReviewAdditionalAttentionNeededIndicator=ConditionToEdit.ReviewAdditionalAttentionNeededIndicator,
                                   ReviewComments=ConditionToEdit.ReviewComments, 
                                   ReviewUserName=ConditionToEdit.ReviewUserName, 
                                   ReviewDateTime=ConditionToEdit.ReviewDateTime,
                                   DeletedIndicator=ConditionToEdit.DeletedIndicator, 
                                   CommandUserName=UserName,
                                   LastModifyDateTime=LastModifyDateTime, 
                                   LastModifyUserName=LastModifyUserName,
                                   ArchivedIndicator=ConditionToEdit.ArchivedIndicator, 
                                   ArchivedUserName=ConditionToEdit.ArchivedUserName, 
                                   ArchivedDateTime=ConditionToEdit.ArchivedDateTime, Objectid=Objectid, 
                                   ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                                   ConditionDepartmentid=ConditionToEdit.ConditionDepartment.id,
                                   PoleConditionStatus=ConditionToEdit.PoleConditionStatus,
                                   GuyAnchorConditionStatus=ConditionToEdit.GuyAnchorConditionStatus,
                                   InsulatorConditionStatus=ConditionToEdit.InsulatorConditionStatus, 
                                   ConductorConditionStatus=ConditionToEdit.ConductorConditionStatus,
                                   RightOfWayConditionStatus=ConditionToEdit.RightOfWayConditionStatus,
                                   PadMountConditionStatus=ConditionToEdit.PadMountConditionStatus,
                                   VaultConditionStatus=ConditionToEdit.VaultConditionStatus,
                                   RiserCableConditionStatus=ConditionToEdit.RiserCableConditionStatus)
            command.Process()
    elif(UpdateIndicator and ApplicationName == djangoproject.settings.COOPGISConditionReviewApplicationName):
        if(Conditionid):  
            ConditionToEdit=Condition.objects.filter(id=Conditionid)[0]
            Objectid, ObjectIndexWhenReverseSorted=ConditionToEdit.GetCommandidData()
            command=Command()
            command=command.Create(Name='EditCondition', PriorityImmediateIndicator=ConditionToEdit.PriorityImmediateIndicator,
                                   PriorityASAPIndicator=ConditionToEdit.PriorityASAPIndicator, 
                                   PriorityRoutineIndicator=ConditionToEdit.PriorityRoutineIndicator,
                                   PriorityEverythingFixedMaintenanceOnlyIndicator=ConditionToEdit.PriorityEverythingFixedMaintenanceOnlyIndicator,
                                   PriorityEverythingOkInspectionOnlyIndicator=ConditionToEdit.PriorityEverythingOkInspectionOnlyIndicator,
                                   PriorityVegetationNeedsAttentionIndicator=ConditionToEdit.PriorityVegetationNeedsAttentionIndicator,
                                   PriorityOutdoorLightingConversionIndicator=False,
                                   PersonReporting=ConditionToEdit.PersonReporting, DateTimeReported=ConditionToEdit.DateTimeReported, 
                                   ReceivedByOperationsIndicator=ConditionToEdit.ReceivedByOperationsIndicator, 
                                   DateTimeReceivedByOperations=ConditionToEdit.DateTimeReceivedByOperations,  
                                   StationIdentifier=ConditionToEdit.StationIdentifier, TagNumber=ConditionToEdit.TagNumber, 
                                   StartPoint=ConditionToEdit.Point,
                                   Description=ConditionToEdit.Description, WorkOrderNumber=ConditionToEdit.WorkOrderNumber,
                                   WorkRemarks=ConditionToEdit.WorkRemarks,
                                   WorkPerformedBy=ConditionToEdit.WorkPerformedBy, 
                                   HoursWorkedQuantity=ConditionToEdit.WorkHours, WorkDate=ConditionToEdit.WorkDate, 
                                   WorkCompletedIndicator=ConditionToEdit.WorkCompletedIndicator, 
                                   WorkNotCompletedIndicator=ConditionToEdit.WorkNotCompletedIndicator,
                                   WorkNotCompletedDescription=ConditionToEdit.WorkNotCompletedDescription, 
                                   WorkForeman=ConditionToEdit.WorkForeman,
                                   WorkForemanSignoffIndicator=ConditionToEdit.WorkForemanSignoffIndicator, 
                                   WorkForemanSignoffDateTime=ConditionToEdit.WorkForemanSignoffDateTime,
                                   ReviewIndicator=ReviewIndicator, 
                                   ReviewAdditionalAttentionNeededIndicator=ReviewAdditionalAttentionNeededIndicator,
                                   ReviewComments=ReviewComments, 
                                   ReviewUserName=ReviewUserName, 
                                   ReviewDateTime=ReviewDateTime,
                                   DeletedIndicator=ConditionToEdit.DeletedIndicator, 
                                   CommandUserName=UserName,
                                   LastModifyDateTime=LastModifyDateTime, 
                                   LastModifyUserName=LastModifyUserName,
                                   ArchivedIndicator=ConditionToEdit.ArchivedIndicator, 
                                   ArchivedUserName=ConditionToEdit.ArchivedUserName, 
                                   ArchivedDateTime=ConditionToEdit.ArchivedDateTime, Objectid=Objectid, 
                                   ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                                   ConditionDepartmentid=ConditionToEdit.ConditionDepartment.id,
                                   PoleConditionStatus=ConditionToEdit.PoleConditionStatus, 
                                   GuyAnchorConditionStatus=ConditionToEdit.GuyAnchorConditionStatus,
                                   InsulatorConditionStatus=ConditionToEdit.InsulatorConditionStatus,
                                   ConductorConditionStatus=ConditionToEdit.ConductorConditionStatus,
                                   RightOfWayConditionStatus=ConditionToEdit.RightOfWayConditionStatus, 
                                   PadMountConditionStatus=ConditionToEdit.PadMountConditionStatus,
                                   VaultConditionStatus=ConditionToEdit.VaultConditionStatus, 
                                   RiserCableConditionStatus=ConditionToEdit.RiserCableConditionStatus)
            command.Process()

def PopulateConditions(form, SelectionStation, NumberOfConditionsListedOnForm):
    if(SelectionStation):
        Conditions=Condition.objects.filter(Point__distance_lte=(SelectionStation.Point, 5)).order_by('id')
    else:
        Conditions=None
    for conditionFormNumber in range(0, NumberOfConditionsListedOnForm + 1):
        try:
            Current=Conditions[conditionFormNumber]
            form.setData({'UpdateIndicator' + str(conditionFormNumber):False})
            form.setData({'Conditionid' + str(conditionFormNumber):str(Current.id)})
            form.setData({'ConditionDepartment' + str(conditionFormNumber):Current.ConditionDepartment.id})
            form.data['PriorityImmediateIndicator' + str(conditionFormNumber)]=Current.PriorityImmediateIndicator
            form.data['PriorityASAPIndicator' + str(conditionFormNumber)]=Current.PriorityASAPIndicator
            form.data['PriorityRoutineIndicator' + str(conditionFormNumber)]=Current.PriorityRoutineIndicator
            form.data['PriorityEverythingFixedMaintenanceOnlyIndicator' + str(conditionFormNumber)]=Current.PriorityEverythingFixedMaintenanceOnlyIndicator
            form.data['PriorityEverythingOkInspectionOnlyIndicator' + str(conditionFormNumber)]=Current.PriorityEverythingOkInspectionOnlyIndicator
            form.data['PriorityVegetationNeedsAttentionIndicator' + str(conditionFormNumber)]=Current.PriorityVegetationNeedsAttentionIndicator
            form.setData({'PoleConditionStatus' + str(conditionFormNumber):Current.PoleConditionStatus.id})
            form.setData({'GuyAnchorConditionStatus' + str(conditionFormNumber):Current.GuyAnchorConditionStatus.id})
            form.setData({'InsulatorConditionStatus' + str(conditionFormNumber):Current.InsulatorConditionStatus.id})
            form.setData({'ConductorConditionStatus' + str(conditionFormNumber):Current.ConductorConditionStatus.id})
            form.setData({'RightOfWayConditionStatus' + str(conditionFormNumber):Current.RightOfWayConditionStatus.id})
            form.setData({'PadMountConditionStatus' + str(conditionFormNumber):Current.PadMountConditionStatus.id})
            form.setData({'VaultConditionStatus' + str(conditionFormNumber):Current.VaultConditionStatus.id})
            form.setData({'RiserCableConditionStatus' + str(conditionFormNumber):Current.RiserCableConditionStatus.id})
            form.data['PersonReporting' + str(conditionFormNumber)]=Current.PersonReporting
            form.data['DateTimeReported' + str(conditionFormNumber)]=Current.DateTimeReported
            form.data['ReceivedByOperationsIndicator' + str(conditionFormNumber)]=Current.ReceivedByOperationsIndicator 
            form.data['DateTimeReceivedByOperations' + str(conditionFormNumber)]=Current.DateTimeReceivedByOperations
            form.data['StationIdentifier' + str(conditionFormNumber)]=Current.StationIdentifier
            form.data['TagNumber' + str(conditionFormNumber)]=Current.TagNumber
            form.data['Description' + str(conditionFormNumber)]=Current.Description
            form.data['WorkOrderNumber' + str(conditionFormNumber)]=Current.WorkOrderNumber
            form.data['WorkRemarks' + str(conditionFormNumber)]=Current.WorkRemarks
            form.data['WorkPerformedBy' + str(conditionFormNumber)]=Current.WorkPerformedBy
            form.data['WorkHours' + str(conditionFormNumber)]=Current.WorkHours
            form.data['WorkDate' + str(conditionFormNumber)]=Current.WorkDate
            form.data['WorkCompletedIndicator' + str(conditionFormNumber)]=Current.WorkCompletedIndicator
            form.data['WorkNotCompletedIndicator' + str(conditionFormNumber)]=Current.WorkNotCompletedIndicator
            form.data['WorkNotCompletedDescription' + str(conditionFormNumber)]=Current.WorkNotCompletedDescription
            form.data['WorkForeman' + str(conditionFormNumber)]=Current.WorkForeman
            form.data['WorkForemanSignoffIndicator' + str(conditionFormNumber)]=Current.WorkForemanSignoffIndicator
            form.data['WorkForemanSignoffDateTime' + str(conditionFormNumber)]=Current.WorkForemanSignoffDateTime
            form.data['ReviewIndicator' + str(conditionFormNumber)]=Current.ReviewIndicator
            form.data['ReviewAdditionalAttentionNeededIndicator' + str(conditionFormNumber)]=Current.ReviewAdditionalAttentionNeededIndicator
            form.data['ReviewComments' + str(conditionFormNumber)]=Current.ReviewComments
            form.data['ReviewUserName' + str(conditionFormNumber)]=Current.ReviewUserName
            form.data['ReviewDateTime' + str(conditionFormNumber)]=Current.ReviewDateTime
            form.data['DeletedIndicator'+ str(conditionFormNumber)]=Current.DeletedIndicator
            form.data['CreateDateTime'+ str(conditionFormNumber)]=Current.CreateDateTime
            form.data['CreateUserName'+ str(conditionFormNumber)]=Current.CreateUserName
            form.data['LastModifyDateTime'+ str(conditionFormNumber)]=Current.LastModifyDateTime
            form.data['LastModifyUserName'+ str(conditionFormNumber)]=Current.LastModifyUserName
            #raise Exception(str('here'))
        except:
            form.data['UpdateIndicator' + str(conditionFormNumber)]=False
            form.data['Conditionid' + str(conditionFormNumber)]='New'
            form.data['ConditionDepartmentid' + str(conditionFormNumber)]=None
            form.data['PriorityImmediateIndicator' + str(conditionFormNumber)]=False
            form.data['PriorityASAPIndicator' + str(conditionFormNumber)]=False
            form.data['PriorityRoutineIndicator' + str(conditionFormNumber)]=False
            form.data['PriorityEverythingFixedMaintenanceOnlyIndicator' + str(conditionFormNumber)]=False
            form.data['PriorityEverythingOkInspectionOnlyIndicator' + str(conditionFormNumber)]=False
            form.data['PriorityVegetationNeedsAttentionIndicator' + str(conditionFormNumber)]=False
            form.data['PoleConditionStatus' + str(conditionFormNumber)]=None
            form.data['GuyAnchorConditionStatus' + str(conditionFormNumber)]=None
            form.data['InsulatorConditionStatus' + str(conditionFormNumber)]=None
            form.data['ConductorConditionStatus' + str(conditionFormNumber)]=None
            form.data['RightOfWayConditionStatus' + str(conditionFormNumber)]=None
            form.data['PadMountConditionStatus' + str(conditionFormNumber)]=None
            form.data['VaultConditionStatus' + str(conditionFormNumber)]=None
            form.data['RiserCableConditionStatus' + str(conditionFormNumber)]=None
            form.data['PersonReporting' + str(conditionFormNumber)]=''
            form.data['DateTimeReported' + str(conditionFormNumber)]=''
            form.data['ReceivedByOperationsIndicator' + str(conditionFormNumber)]=False 
            form.data['DateTimeReceivedByOperations' + str(conditionFormNumber)]=''
            form.data['StationIdentifier' + str(conditionFormNumber)]=''
            form.data['TagNumber' + str(conditionFormNumber)]=''
            form.data['Description' + str(conditionFormNumber)]=''
            form.data['WorkOrderNumber' + str(conditionFormNumber)]=''
            form.data['WorkRemarks' + str(conditionFormNumber)]=''
            form.data['WorkPerformedBy' + str(conditionFormNumber)]=''
            form.data['WorkHours' + str(conditionFormNumber)]=''
            form.data['WorkDate' + str(conditionFormNumber)]=''
            form.data['WorkCompletedIndicator' + str(conditionFormNumber)]=False
            form.data['WorkNotCompletedIndicator' + str(conditionFormNumber)]=False
            form.data['WorkNotCompletedDescription' + str(conditionFormNumber)]=''
            form.data['WorkForeman' + str(conditionFormNumber)]=''
            form.data['WorkForemanSignoffIndicator' + str(conditionFormNumber)]=False
            form.data['WorkForemanSignoffDateTime' + str(conditionFormNumber)]=''
            form.data['ReviewIndicator' + str(conditionFormNumber)]=False
            form.data['ReviewAdditionalAttentionNeededIndicator' + str(conditionFormNumber)]=False
            form.data['ReviewComments' + str(conditionFormNumber)]=''
            form.data['ReviewUserName' + str(conditionFormNumber)]=''
            form.data['ReviewDateTime' + str(conditionFormNumber)]=''
            form.data['DeletedIndicator'+ str(conditionFormNumber)]=False
            form.data['CreateDateTime'+ str(conditionFormNumber)]=''
            form.data['CreateUserName'+ str(conditionFormNumber)]=''
            form.data['LastModifyDateTime'+ str(conditionFormNumber)]=''
            form.data['LastModifyUserName'+ str(conditionFormNumber)]=''



def CalculateConditionCreateData(UserName, Conditionid):
    try:
        condition=Condition.objects.filter(id=Conditionid)[0]
    except:
        condition=None  
    if(condition):
        LastModifyDateTime=datetime.datetime.now()
    else:
        CreateDateTime=datetime.datetime.now()
        LastModifyDateTime=CreateDateTime
    LastModifyUserName=UserName
    return LastModifyDateTime, LastModifyUserName


def CalculateConditionPoint(Conditionid, FormStationIdentifier, FormTagNumber, SelectionStation):
    """Calculates where the condition should be, in the following priority order:
       Form Station Identifier
       Form TagNumber
       Condition Point
       SelectionStation.Point"""
    try:
        condition=Condition.objects.filter(id=Conditionid)[0]
    except:
        condition=None  
    FoundPoint=False    
    if(FormStationIdentifier):
        try:
            station=Station.objects.filter(id=FormStationIdentifier)[0]
            point=station.Point
            FoundPoint=True
        except:
            pass
    if(not FoundPoint and FormTagNumber):
        try:
            pole=Assembly.objects.filter(TagNumber__istartswith=FormTagNumber)[0]
            point=pole.Station.Point
            station=pole.Station
            FoundPoint=True
        except:
            pass
    if(not FoundPoint and condition):
        point=condition.Point
        station=Station.objects.filter(distance__lte=(point, 1))[0]
    elif(SelectionStation):
        station=SelectionStation
        point=SelectionStation.Point
    elif(not FoundPoint):
        point=None
        station=None
    if(station):
        StationIdentifier=station.id
    else:
        StationIdentifier=''
    return point, StationIdentifier 



def GetConditionsListedOnDispatchForm(request):
    try:     
        ShowAllIndicator=bool(request.POST['ShowAllIndicator'] == 'on')
    except:
        ShowAllIndicator=False
    try:
        OnlyShowVegetationIndicator=bool(request.POST['OnlyShowVegetationIndicator'] == 'on')
    except:
        OnlyShowVegetationIndicator=False
    try:
        OnlyShowArchivedIndicator=bool(request.POST['OnlyShowArchivedIndicator'] == 'on')
    except:
        OnlyShowArchivedIndicator=False

    if(ShowAllIndicator):
        return Condition.objects.all()
    elif(OnlyShowVegetationIndicator):
        if(OnlyShowArchivedIndicator):
            return Condition.objects.all().filter(PriorityVegetationNeedsAttentionIndicator=True).filter(ArchivedIndicator=True)
        else:
            return Condition.objects.all().filter(PriorityVegetationNeedsAttentionIndicator=True)
    elif(OnlyShowArchivedIndicator):
        return Condition.objects.all().filter(ArchivedIndicator=True).exclude(PriorityVegetationNeedsAttentionIndicator=True)       
    else:
        return Condition.objects.all().exclude(PriorityEverythingFixedMaintenanceOnlyIndicator=True).\
                         exclude(PriorityEverythingOkInspectionOnlyIndicator=True).\
                         exclude(PriorityVegetationNeedsAttentionIndicator=True).\
                         exclude(ArchivedIndicator=True)


def GetAssignmentChoicesList(Default=''):
    Users=User.objects.filter(groups__name=djangoproject.settings.COOPGISConditionAssignmentUserApplicationName).order_by('username')
    DefaultUser=None
    if(Default):
        try:
            DefaultUser=User.objects.filter(groups__name=djangoproject.settings.COOPGISConditionAssignmentUserApplicationName).filter(username=Default)[0]
        except:
            DefaultUser=None
          
    AssignmentUserChoices=[[-1, 'None']]
    for user in Users:
        AssignmentUserChoices.append([user.id, user.username])
    return AssignmentUserChoices


def BuildConditionDispatchForm(request):
    NumberOfConditionsListedOnForm=GetConditionsListedOnDispatchForm(request).count()
    Dict={}
    #Build ConditionDepartment Choices List
    ConditionDepartmentChoices=[]
    ConditionDepartments=ConditionDepartment.objects.all().order_by('Name')
    for i in ConditionDepartments:
        ConditionDepartmentChoices.append([i.id, str(i.Name)])
    AssignmentChoices=GetAssignmentChoicesList()
    #General Fields for selecting the map and running queries
    Dict['ShowAllIndicator']=forms.BooleanField()
    Dict['OnlyShowVegetationIndicator']=forms.BooleanField()
    Dict['OnlyShowArchivedIndicator']=forms.BooleanField()
    for i in range(0, NumberOfConditionsListedOnForm):
        Dict['UpdateIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['Conditionid' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['ConditionDepartment' + str(i)]=forms.ChoiceField(ConditionDepartmentChoices, required=False)
        Dict['CurrentAssignment' + str(i)] = forms.ChoiceField(AssignmentChoices, required=False)
        Dict['StationIdentifier' + str(i)]=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
        Dict['TagNumber' + str(i)]=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['PriorityString' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'8', 'READONLY':'True'}))
        Dict['DateTimeReported' + str(i)]=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'7'}))
        Dict['Description' + str(i)]=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3, 'cols':30}))        
        Dict['WorkOrderNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['WorkRemarks' + str(i)]=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3, 'cols':30})) 
        Dict['WorkPerformedBy' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['WorkHours' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['WorkDate' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'7'}))
        Dict['WorkCompletedIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['WorkNotCompletedIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['WorkNotCompletedDescription' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
        Dict['ReviewIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['ReviewComments' + str(i)]=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3, 'cols':30})) 
        Dict['ReviewAdditionalAttentionNeededIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['ArchivedIndicator' + str(i)]=forms.BooleanField(required=False)
    return Dict, NumberOfConditionsListedOnForm


def ProcessConditionDispatchFormEntry(form, ConditionNumber, UserName):
    """Processes the Condition Dispatch Form to edit Hazard Conditions Reports in a table format"""
    ConditionNumber=str(ConditionNumber)
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator' + ConditionNumber)
    if(not UpdateIndicator):
        return
    Conditionid=COOPGIS_FormMisc.FormGetString(form, 'Conditionid' + ConditionNumber, '')
    if(Conditionid):
        condition=Condition.objects.filter(id=Conditionid)[0]
    else:
        return
    ConditionDepartmentid=COOPGIS_FormMisc.FormGetInteger(form, 'ConditionDepartment' + ConditionNumber, '')
    conditionDepartment=ConditionDepartment.objects.filter(id=ConditionDepartmentid)[0]
    PriorityImmediateIndicator=condition.PriorityImmediateIndicator
    PriorityASAPIndicator=condition.PriorityASAPIndicator
    PriorityRoutineIndicator=condition.PriorityRoutineIndicator 
    PriorityEverythingFixedMaintenanceOnlyIndicator=condition.PriorityEverythingFixedMaintenanceOnlyIndicator
    PriorityEverythingOkInspectionOnlyIndicator=condition.PriorityEverythingOkInspectionOnlyIndicator
    PriorityVegetationNeedsAttentionIndicator=condition.PriorityVegetationNeedsAttentionIndicator
    PersonReporting=condition.PersonReporting
    DateTimeReported=condition.DateTimeReported
    ReceivedByOperationsIndicator=condition.ReceivedByOperationsIndicator
    DateTimeReceivedByOperations=condition.DateTimeReceivedByOperations
 
    StationIdentifier=COOPGIS_FormMisc.FormGetString(form, 'StationIdentifier' + ConditionNumber)
    TagNumber=COOPGIS_FormMisc.FormGetString(form, 'TagNumber' + ConditionNumber)
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description' + ConditionNumber)
    WorkOrderNumber=condition.WorkOrderNumber
    WorkRemarks=COOPGIS_FormMisc.FormGetString(form, 'WorkRemarks' + ConditionNumber)
    WorkPerformedBy=COOPGIS_FormMisc.FormGetString(form, 'WorkPerformedBy' + ConditionNumber) 
    WorkHours=COOPGIS_FormMisc.FormGetFloat(form, 'WorkHours' + ConditionNumber)
    WorkDate=COOPGIS_FormMisc.FormGetDateTime(form, 'WorkDate' + ConditionNumber) 
    WorkCompletedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'WorkCompletedIndicator' + ConditionNumber)
    WorkNotCompletedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'WorkNotCompletedIndicator' + ConditionNumber)
    WorkNotCompletedDescription=COOPGIS_FormMisc.FormGetString(form, 'WorkNotCompletedDescription' + ConditionNumber)
    WorkForeman=condition.WorkForeman
    WorkForemanSignoffIndicator=condition.WorkForemanSignoffIndicator
    WorkForemanSignoffDateTime=condition.WorkForemanSignoffDateTime
    ReviewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ReviewIndicator' + ConditionNumber)
    ReviewAdditionalAttentionNeededIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ReviewAdditionalAttentionNeededIndicator' + ConditionNumber)
    ReviewComments=COOPGIS_FormMisc.FormGetString(form, 'ReviewComments' + ConditionNumber)
    ReviewUserName=condition.ReviewUserName
    ReviewDateTime=condition.ReviewDateTime
    
    ArchivedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ArchivedIndicator' + ConditionNumber)
    if(ArchivedIndicator and not condition.ArchivedIndicator):
        ArchivedUserName=UserName
        ArchivedDateTime=datetime.datetime.now()
    else:
        ArchivedUserName=condition.ArchivedUserName
        ArchivedDateTime=condition.ArchivedDateTime

    DeletedIndicator=condition.DeletedIndicator
    LastModifyDateTime, LastModifyUserName=CalculateConditionCreateData(UserName, Conditionid)
    point, StationIdentifier = CalculateConditionPoint(Conditionid, StationIdentifier, TagNumber, SelectionStation=None)
    if(UpdateIndicator):
        Objectid, ObjectIndexWhenReverseSorted=condition.GetCommandidData()
        command=Command()
        command=command.Create(Name='EditCondition', ConditionDepartment=conditionDepartment,
                               PriorityImmediateIndicator=PriorityImmediateIndicator,
                               PriorityASAPIndicator=PriorityASAPIndicator, 
                               PriorityRoutineIndicator=PriorityRoutineIndicator,
                               PriorityEverythingFixedMaintenanceOnlyIndicator=PriorityEverythingFixedMaintenanceOnlyIndicator,
                               PriorityEverythingOkInspectionOnlyIndicator=PriorityEverythingOkInspectionOnlyIndicator,
                               PriorityVegetationNeedsAttentionIndicator=PriorityVegetationNeedsAttentionIndicator,
                               PriorityOutdoorLightingConversionIndicator=False,
                               PersonReporting=PersonReporting, DateTimeReported=DateTimeReported, 
                               ReceivedByOperationsIndicator=ReceivedByOperationsIndicator, 
                               DateTimeReceivedByOperations=DateTimeReceivedByOperations, 
                               StationIdentifier=StationIdentifier, TagNumber=TagNumber, 
                               StartPoint=point,
                               Description=Description, WorkOrderNumber=WorkOrderNumber,
                               WorkRemarks=WorkRemarks,
                               WorkPerformedBy=WorkPerformedBy, 
                               HoursWorkedQuantity=WorkHours, WorkDate=WorkDate, 
                               WorkCompletedIndicator=WorkCompletedIndicator, 
                               WorkNotCompletedIndicator=WorkNotCompletedIndicator,
                               WorkNotCompletedDescription=WorkNotCompletedDescription, 
                               WorkForeman=WorkForeman,
                               WorkForemanSignoffIndicator=WorkForemanSignoffIndicator, 
                               WorkForemanSignoffDateTime=WorkForemanSignoffDateTime,
                               ReviewIndicator=ReviewIndicator, 
                               ReviewAdditionalAttentionNeededIndicator=ReviewAdditionalAttentionNeededIndicator,
                               ReviewComments=ReviewComments, 
                               ReviewUserName=ReviewUserName, 
                               ReviewDateTime=ReviewDateTime,
                               DeletedIndicator=DeletedIndicator, 
                               CommandUserName=UserName,
                               LastModifyDateTime=LastModifyDateTime, 
                               LastModifyUserName=LastModifyUserName,
                               ArchivedIndicator=ArchivedIndicator, 
                               ArchivedUserName=ArchivedUserName, 
                               ArchivedDateTime=ArchivedDateTime, Objectid=Objectid, 
                               ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                               ConditionDepartmentid=ConditionDepartmentid)
        command.Process()



def DispatchFormOrderConditions(Conditions):
    Conditions=Conditions.order_by('id')
    OrderedConditions=[]
    for i in Conditions:
        if(i.PriorityImmediateIndicator and not i in OrderedConditions):
            OrderedConditions.append(i)
    for i in Conditions:
        if(i.PriorityASAPIndicator and not i in OrderedConditions):
            OrderedConditions.append(i)
    for i in Conditions:
        if(i.PriorityRoutineIndicator and not i in OrderedConditions):
            OrderedConditions.append(i)
    for i in Conditions:
        if(not i in OrderedConditions):
            OrderedConditions.append(i)
    return OrderedConditions  

def PopulateDispatchConditions(form, request, NumberOfConditionsListedOnForm):
    Conditions=GetConditionsListedOnDispatchForm(request)
    Conditions=DispatchFormOrderConditions(Conditions)
    for conditionFormNumber in range(0, NumberOfConditionsListedOnForm):
        try:
            Current=Conditions[conditionFormNumber]
            form.data['UpdateIndicator' + str(conditionFormNumber)]=False
            form.data['Conditionid' + str(conditionFormNumber)]=Current.id
            form.data['ConditionDeparment' + str(conditionFormNumber)]=Current.ConditionDepartment.id
            CurrentAssignmentUser=Current.GetCurrentAssignmentUser()
            if(CurrentAssignmentUser):
                form.setData({'CurrentAssignment':CurrentAssignmentUser.id})
            else:
                form.data['CurrentAssignment' + str(conditionFormNumber)]=''
            form.data['StationIdentifier' + str(conditionFormNumber)]=Current.StationIdentifier
            form.data['TagNumber' + str(conditionFormNumber)]=Current.TagNumber
            form.data['PriorityString' + str(conditionFormNumber)]=Current.GetPriorityString()
            form.data['DateTimeReported' + str(conditionFormNumber)]=Current.DateTimeReported
            form.data['Description' + str(conditionFormNumber)]=Current.Description
            form.data['WorkRemarks' + str(conditionFormNumber)]=Current.WorkRemarks
            form.data['ReviewComments' + str(conditionFormNumber)]=Current.ReviewComments
            form.data['WorkOrderNumber' + str(conditionFormNumber)]=Current.WorkOrderNumber
            form.data['WorkPerformedBy' + str(conditionFormNumber)]=Current.WorkPerformedBy
            form.data['WorkHours' + str(conditionFormNumber)]=Current.WorkHours
            form.data['WorkDate' + str(conditionFormNumber)]=Current.WorkDate
            form.data['WorkCompletedIndicator' + str(conditionFormNumber)] =Current.WorkCompletedIndicator
            form.data['WorkNotCompletedIndicator' + str(conditionFormNumber)] =Current.WorkNotCompletedIndicator
            form.data['WorkNotCompletedDescription' + str(conditionFormNumber)]=Current.WorkNotCompletedDescription
            form.data['ReviewIndicator' + str(conditionFormNumber)] =Current.ReviewIndicator
            form.data['ReviewAdditionalAttentionNeededIndicator' + str(conditionFormNumber)]=Current.ReviewAdditionalAttentionNeededIndicator 
            form.data['ArchivedIndicator' + str(conditionFormNumber)]=Current.ArchivedIndicator
        except:
            form.data['UpdateIndicator' + str(conditionFormNumber)]=False
            form.data['Conditionid' + str(conditionFormNumber)]=''
            form.data['ConditionDeparment' + str(conditionFormNumber)]=''
            form.data['CurrentAssignmentUser' + str(conditionFormNumber)]=''
            form.data['StationIdentifier' + str(conditionFormNumber)]=''
            form.data['TagNumber' + str(conditionFormNumber)]=''
            form.data['PriorityString' + str(conditionFormNumber)]=''
            form.data['DateTimeReported' + str(conditionFormNumber)]=''
            form.data['Description' + str(conditionFormNumber)]=''
            form.data['WorkRemarks' + str(conditionFormNumber)]=''
            form.data['ReviewComments' + str(conditionFormNumber)]=''
            form.data['WorkOrderNumber' + str(conditionFormNumber)]=''
            form.data['WorkPerformedBy' + str(conditionFormNumber)]=''
            form.data['WorkHours' + str(conditionFormNumber)]=''
            form.data['WorkDate' + str(conditionFormNumber)]=''
            form.data['WorkCompletedIndicator' + str(conditionFormNumber)]=False 
            form.data['WorkNotCompletedIndicator' + str(conditionFormNumber)]=False 
            form.data['WorkNotCompletedDescription' + str(conditionFormNumber)]=''
            form.data['ReviewIndicator' + str(conditionFormNumber)]=False 
            form.data['ReviewAdditionalAttentionNeededIndicator' + str(conditionFormNumber)]=False 
            form.data['ArchivedIndicator' + str(conditionFormNumber)]=False
    return form


def BuildOutdoorLightingForm(DefaultMap, point=None):
    NumberOfConditionsListedOnForm=GetNumberOfOutdoorLightsListedOnForm(point=point)
    Dict={}
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([DefaultMap.id, str(DefaultMap.Name)[:30]])
    Maps=Map.objects.all().order_by('Name')
    for i in Maps:
        if(not i == DefaultMap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    #Build ConditionDepartment Choices List
    ConditionDepartmentChoices=[]
    ConditionDepartments=ConditionDepartment.objects.all().order_by('id')
    for i in ConditionDepartments:
        ConditionDepartmentChoices.append([i.id, str(i.Name)])
    #General Fields for selecting the map and running queries
    ConditionStatusChoices=[]
    ConditionStatuses=ConditionStatus.objects.all().order_by('Name')
    for i in ConditionStatuses:
        ConditionStatusChoices.append([i.id, str(i)])
    OutdoorLightRateChoices=[]
    OutdoorLightRateChoices.append(['-1', 'None'])
    OutdoorLightRates=OutdoorLightRate.objects.all().order_by('id')
    for i in OutdoorLightRates:
        OutdoorLightRateChoices.append([i.id, str(i)])
    OutdoorLightProblemCodeChoices=[]
    OutdoorLightProblemCodeChoices.append(['-1', 'None'])
    OutdoorLightProblemCodes = OutdoorLightProblemCode.objects.all().order_by('id')
    for i in OutdoorLightProblemCodes:
        OutdoorLightProblemCodeChoices.append([i.id, str(i)])
    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    Dict['SelectMapNumber']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SelectRoadName']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SelectStationTagNumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'6'}))
    Dict['SelectStationid']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'6'}))
    Dict['SelectMeterNumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SelectDCSINumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'10'}))
    Dict['SelectGPSIndicator']=forms.BooleanField()
    Dict['StationComment']=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
    Dict['UpdateStationCommentIndicator']=forms.BooleanField(required=False)
    Dict['AssembliesAtSelectionStation']=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3, 'cols':40, 'READONLY':'True'}))
    for i in range(0, NumberOfConditionsListedOnForm):
        Dict['UpdateIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['Conditionid' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['ConditionDepartment' + str(i)]=forms.ChoiceField(ConditionDepartmentChoices, required=False)
        Dict['PriorityImmediateIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['PriorityASAPIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['PriorityRoutineIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['PriorityEverythingFixedMaintenanceOnlyIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['PriorityEverythingOkInspectionOnlyIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['PriorityVegetationNeedsAttentionIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['PriorityOutdoorLightingConversionIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['NeedsRetirementIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['PoleConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['GuyAnchorConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['InsulatorConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['ConductorConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['RightOfWayConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['PadMountConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['VaultConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['RiserCableConditionStatus' + str(i)]=forms.ChoiceField(ConditionStatusChoices, required=False)
        Dict['ConditionMemberDescription' + str(i)] = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3, 'cols':40}))
        Dict['OutdoorLightMapNumber' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
        Dict['OutdoorLightMeterNumber' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
        Dict['OutdoorLightMeterMapNumber' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15'}))
        Dict['OutdoorLightIdleIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['OutdoorLightCustomerOwnsPoleIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['OutdoorLightCustomerOwnsLightIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['OutdoorLightRate' + str(i)] = forms.ChoiceField(OutdoorLightRateChoices, required=False)
        Dict['OutdoorLightProblemCode' + str(i)] = forms.ChoiceField(OutdoorLightProblemCodeChoices, required=False)
        Dict['OutdoorLightAdditionalBillingPoleCount' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['OutdoorLightConsumerOwnedLightCount' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4'}))
        Dict['OutdoorLightBillingWorkStartedNotificationString' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'15', 'READONLY':'True'}))
        Dict['PersonReporting' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'9'}))
        Dict['DateTimeReported' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['ReceivedByOperationsIndicator' + str(i)] = forms.BooleanField(required=False) 
        Dict['DateTimeReceivedByOperations' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['StationIdentifier' + str(i)]=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
        Dict['TagNumber' + str(i)]=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['Description' + str(i)]=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3, 'cols':40}))
        Dict['WorkOrderNumber' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['WorkRemarks' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
        Dict['WorkPerformedBy' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['WorkHours' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['WorkDate' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['WorkCompletedIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['WorkNotCompletedIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['WorkNotCompletedDescription' + str(i)] = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3, 'cols':40}))
        Dict['WorkForeman' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['WorkForemanSignoffIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['WorkForemanSignoffDateTime' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['ReviewIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['ReviewAdditionalAttentionNeededIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['ReviewComments' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
        Dict['ReviewUserName' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['ReviewDateTime' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['DeletedIndicator'+ str(i)]=forms.BooleanField(required=False)
        Dict['ArchivedUserName' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['ArchivedDateTime' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['ArchivedIndicator'+ str(i)]=forms.BooleanField(required=False)
        #Dict['CreateDateTime'+ str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6', 'READONLY':'True'}))
        #Dict['CreateUserName'+ str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6', 'READONLY':'True'}))
        Dict['LastModifyDateTime'+ str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6', 'READONLY':'True'}))
        Dict['LastModifyUserName'+ str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6', 'READONLY':'True'}))

    return Dict

def ProcessOutdoorLightingFormEntry(form, ConditionNumber, SelectionStation, UserName, ApplicationName):
    """Processes the ConditionEditor Form to create new Hazard Condition Reports or Edit exiting Ones."""
    if(not SelectionStation):
        return #Changes cannot be made to Condition Reports if there is not a current station at the report site
    ConditionNumber=str(ConditionNumber)
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator' + ConditionNumber)
    Conditionid=COOPGIS_FormMisc.FormGetString(form, 'Conditionid' + ConditionNumber, 'New')
    ConditionDepartmentid=COOPGIS_FormMisc.FormGetInteger(form, 'ConditionDepartment' + ConditionNumber)
    PriorityImmediateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PriorityImmediateIndicator' + ConditionNumber)
    PriorityASAPIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PriorityASAPIndicator' + ConditionNumber)
    PriorityRoutineIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PriorityRoutineIndicator' + ConditionNumber)
    PriorityEverythingFixedMaintenanceOnlyIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PriorityEverythingFixedMaintenanceOnlyIndicator' + ConditionNumber)
    PriorityEverythingOkInspectionOnlyIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PriorityEverythingOkInspectionOnlyIndicator' + ConditionNumber)
    PriorityVegetationNeedsAttentionIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PriorityVegetationNeedsAttentionIndicator' + ConditionNumber)
    PriorityOutdoorLightingConversionIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'PriorityOutdoorLightingConversionIndicator' + ConditionNumber)
    NeedsRetirementIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'NeedsRetirementIndicator' + ConditionNumber)
    PoleConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'PoleConditionStatus' + ConditionNumber)
    GuyAnchorConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'GuyAnchorConditionStatus' + ConditionNumber)
    InsulatorConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'InsulatorConditionStatus' + ConditionNumber)
    ConductorConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'ConductorConditionStatus' + ConditionNumber)
    RightOfWayConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'RightOfWayConditionStatus' + ConditionNumber)
    PadMountConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'PadMountConditionStatus' + ConditionNumber)
    VaultConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'VaultConditionStatus' + ConditionNumber)
    RiserCableConditionStatus=COOPGIS_FormMisc.FormGetInteger(form, 'RiserCableConditionStatus' + ConditionNumber)
    ConditionMemberDescription=COOPGIS_FormMisc.FormGetString(form, 'ConditionMemberDescription' + ConditionNumber)
    OutdoorLightMapNumber=COOPGIS_FormMisc.FormGetString(form, 'OutdoorLightMapNumber' + ConditionNumber)
    OutdoorLightMeterNumber=COOPGIS_FormMisc.FormGetString(form, 'OutdoorLightMeterNumber' + ConditionNumber)
    OutdoorLightMeterMapNumber=COOPGIS_FormMisc.FormGetString(form, 'OutdoorLightMeterMapNumber' + ConditionNumber)
    OutdoorLightIdleIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'OutdoorLightIdleIndicator' + ConditionNumber)
    OutdoorLightCustomerOwnsPoleIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'OutdoorLightCustomerOwnsPoleIndicator' + ConditionNumber)
    OutdoorLightCustomerOwnsLightIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'OutdoorLightCustomerOwnsLightIndicator'+ ConditionNumber)
    OutdoorLightRateid=COOPGIS_FormMisc.FormGetInteger(form, 'OutdoorLightRate' + ConditionNumber)
    OutdoorLightProblemCodeid=COOPGIS_FormMisc.FormGetInteger(form, 'OutdoorLightProblemCode' + ConditionNumber)
    OutdoorLightAdditionalBillingPoleCount = COOPGIS_FormMisc.FormGetInteger(form, 'OutdoorLightAdditionalBillingPoleCount' + ConditionNumber)
    OutdoorLightConsumerOwnedLightCount=COOPGIS_FormMisc.FormGetInteger(form, 'OutdoorLightConsumerOwnedLightCount' + ConditionNumber)
    PersonReporting=COOPGIS_FormMisc.FormGetString(form, 'PersonReporting' + ConditionNumber)
    DateTimeReported=COOPGIS_FormMisc.FormGetDateTime(form, 'DateTimeReported' + ConditionNumber)
    ReceivedByOperationsIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ReceivedByOperationsIndicator' + ConditionNumber)
    DateTimeReceivedByOperations=COOPGIS_FormMisc.FormGetDateTime(form, 'DateTimeReceivedByOperations' + ConditionNumber)
    StationIdentifier=COOPGIS_FormMisc.FormGetString(form, 'StationIdentifier' + ConditionNumber)
    TagNumber=COOPGIS_FormMisc.FormGetString(form, 'TagNumber' + ConditionNumber)
    Description=COOPGIS_FormMisc.FormGetString(form, 'Description' + ConditionNumber)
    WorkOrderNumber=COOPGIS_FormMisc.FormGetString(form, 'WorkOrderNumber' + ConditionNumber)
    WorkRemarks=COOPGIS_FormMisc.FormGetString(form, 'WorkRemarks' + ConditionNumber)
    WorkPerformedBy=COOPGIS_FormMisc.FormGetString(form, 'WorkPerformedBy' + ConditionNumber)
    WorkHours=COOPGIS_FormMisc.FormGetFloat(form, 'WorkHours' + ConditionNumber)
    WorkDate=COOPGIS_FormMisc.FormGetDateTime(form, 'WorkDate' + ConditionNumber)
    WorkCompletedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'WorkCompletedIndicator' + ConditionNumber)
    WorkNotCompletedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'WorkNotCompletedIndicator' + ConditionNumber)
    WorkNotCompletedDescription=COOPGIS_FormMisc.FormGetString(form, 'WorkNotCompletedDescription' + ConditionNumber)
    WorkForeman=COOPGIS_FormMisc.FormGetString(form, 'WorkForeman' + ConditionNumber)
    WorkForemanSignoffIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'WorkForemanSignoffIndicator' + ConditionNumber)
    WorkForemanSignoffDateTime=COOPGIS_FormMisc.FormGetDateTime(form, 'WorkForemanSignoffDateTime' + ConditionNumber)
    ReviewIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ReviewIndicator' + ConditionNumber)
    ReviewAdditionalAttentionNeededIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ReviewAdditionalAttentionNeededIndicator' + ConditionNumber)
    ReviewComments=COOPGIS_FormMisc.FormGetString(form, 'ReviewComments' + ConditionNumber)
    ReviewUserName=COOPGIS_FormMisc.FormGetString(form, 'ReviewUserName' + ConditionNumber)
    ReviewDateTime=COOPGIS_FormMisc.FormGetDateTime(form, 'ReviewDateTime' + ConditionNumber)
    ArchivedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'ArchivedIndicator' + ConditionNumber)
    ArchivedUserName=COOPGIS_FormMisc.FormGetString(form, 'ArchivedUserName' + ConditionNumber)
    ArchivedDateTime=COOPGIS_FormMisc.FormGetDateTime(form, 'ArchivedDateTime' + ConditionNumber)
    DeletedIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'DeletedIndicator' + ConditionNumber)
    LastModifyDateTime, LastModifyUserName=CalculateConditionCreateData(UserName, Conditionid)
    point, StationIdentifier = CalculateConditionPoint(Conditionid, StationIdentifier, TagNumber, SelectionStation)
    if UpdateIndicator:
        if(Conditionid == 'New' or not Conditionid):   
            command=Command()
            command=command.Create(Name='CreateCondition',
                                   CommandUserName=UserName,
                                   CommandCreateDateTime=datetime.datetime.now(),
                                   PriorityImmediateIndicator=PriorityImmediateIndicator,
                                   PriorityASAPIndicator=PriorityASAPIndicator, PriorityRoutineIndicator=PriorityRoutineIndicator,
                                   PriorityEverythingFixedMaintenanceOnlyIndicator=PriorityEverythingFixedMaintenanceOnlyIndicator,
                                   PriorityEverythingOkInspectionOnlyIndicator=PriorityEverythingOkInspectionOnlyIndicator,
                                   PriorityVegetationNeedsAttentionIndicator=PriorityVegetationNeedsAttentionIndicator,
                                   PriorityOutdoorLightingConversionIndicator=PriorityOutdoorLightingConversionIndicator,
                                   NeedsRetirementIndicator=NeedsRetirementIndicator,
                                   PersonReporting=PersonReporting, DateTimeReported=DateTimeReported, 
                                   ReceivedByOperationsIndicator=ReceivedByOperationsIndicator, 
                                   DateTimeReceivedByOperations=DateTimeReceivedByOperations, 
                                   StationIdentifier=StationIdentifier, TagNumber=TagNumber, StartPoint=point,
                                   Description=Description, WorkOrderNumber='', WorkRemarks='',
                                   WorkPerformedBy='', HoursWorkedQuantity=0, WorkDate=None, 
                                   WorkCompletedIndicator=False, 
                                   WorkNotCompletedIndicator=False,
                                   WorkNotCompletedDescription='', WorkForeman='',
                                   WorkForemanSignoffIndicator=False, 
                                   WorkForemanSignoffDateTime=None,
                                   ReviewIndicator=False, 
                                   ReviewAdditionalAttentionNeededIndicator=False,
                                   ReviewComments='', ReviewUserName='', ReviewDateTime=None,
                                   DeletedIndicator=False,
                                   LastModifyDateTime=None, LastModifyUserName='',
                                   ArchivedIndicator=False, ArchivedUserName='', 
                                   ArchivedDateTime=None, ConditionDepartmentid=ConditionDepartmentid,
                                   PoleConditionStatus=PoleConditionStatus, GuyAnchorConditionStatus=GuyAnchorConditionStatus,
                                   InsulatorConditionStatus=InsulatorConditionStatus, ConductorConditionStatus=ConductorConditionStatus,
                                   RightOfWayConditionStatus=RightOfWayConditionStatus, PadMountConditionStatus=PadMountConditionStatus,
                                   VaultConditionStatus=VaultConditionStatus, RiserCableConditionStatus=RiserCableConditionStatus,
                                   OutdoorLightMapNumber=OutdoorLightMapNumber,
                                   OutdoorLightMeterNumber=OutdoorLightMeterNumber,
                                   OutdoorLightMeterMapNumber=OutdoorLightMeterMapNumber,
                                   OutdoorLightIdleIndicator=OutdoorLightIdleIndicator,
                                   OutdoorLightCustomerOwnsPoleIndicator=OutdoorLightCustomerOwnsPoleIndicator,
                                   OutdoorLightCustomerOwnsLightIndicator=OutdoorLightCustomerOwnsLightIndicator,
                                   OutdoorLightRateid=OutdoorLightRateid,
                                   OutdoorLightProblemCodeid=OutdoorLightProblemCodeid,
                                   OutdoorLightAdditionalBillingPoleCount = OutdoorLightAdditionalBillingPoleCount,
                                   OutdoorLightConsumerOwnedLightCount=OutdoorLightConsumerOwnedLightCount,
                                   OutdoorLightGISPhaseIndicator=True, OutdoorLightSendBackToBillingPhaseIndicator=None)
        
            condition=command.Process()
            if ConditionMemberDescription:
                command2 = Command()
                Conditionid, ConditionIndexWhenReverseSorted=condition.GetCommandidData()
                command2 = command2.Create(Name='CreateConditionMemberDescriptionHistory',
                                          CommandUserName = UserName,
                                          CommandCreateDateTime= datetime.datetime.now(),
                                          Conditionid = Conditionid, ConditionIndexWhenReverseSorted=ConditionIndexWhenReverseSorted,
                                          Description=ConditionMemberDescription)
                command2.Process()
        elif(Conditionid):  
            ConditionToEdit=Condition.objects.filter(id=Conditionid)[0]
            if ConditionToEdit.OutdoorLightBillingWorkStartedIndicator and not ConditionToEdit.OutdoorLightGISPhaseIndicator:
                return  #Field personnel not allowed to edit Outdoor Lighting Conditions that have already gone on to office personnel
                         #unless they have already been sent back
            Objectid, ObjectIndexWhenReverseSorted=ConditionToEdit.GetCommandidData()
            command=Command()
            command=command.Create(Name='EditCondition',
                                   CommandUserName = UserName, 
                                   CommandCreateDateTime = datetime.datetime.now(),
                                   PriorityImmediateIndicator=PriorityImmediateIndicator,
                                   PriorityASAPIndicator=PriorityASAPIndicator, PriorityRoutineIndicator=PriorityRoutineIndicator,
                                   PriorityEverythingFixedMaintenanceOnlyIndicator=PriorityEverythingFixedMaintenanceOnlyIndicator,
                                   PriorityEverythingOkInspectionOnlyIndicator=PriorityEverythingOkInspectionOnlyIndicator,
                                   PriorityVegetationNeedsAttentionIndicator=PriorityVegetationNeedsAttentionIndicator,
                                   PriorityOutdoorLightingConversionIndicator=PriorityOutdoorLightingConversionIndicator,
                                   NeedsRetirementIndicator=NeedsRetirementIndicator, 
                                   PersonReporting=PersonReporting, DateTimeReported=DateTimeReported, 
                                   ReceivedByOperationsIndicator=ReceivedByOperationsIndicator, 
                                   DateTimeReceivedByOperations=DateTimeReceivedByOperations, 
                                   StationIdentifier=StationIdentifier, TagNumber=TagNumber, StartPoint=point,
                                   Description=Description, WorkOrderNumber=ConditionToEdit.WorkOrderNumber,
                                   WorkRemarks=ConditionToEdit.WorkRemarks,
                                   WorkPerformedBy=ConditionToEdit.WorkPerformedBy, 
                                   HoursWorkedQuantity=ConditionToEdit.WorkHours, WorkDate=ConditionToEdit.WorkDate, 
                                   WorkCompletedIndicator=ConditionToEdit.WorkCompletedIndicator, 
                                   WorkNotCompletedIndicator=ConditionToEdit.WorkNotCompletedIndicator,
                                   WorkNotCompletedDescription=ConditionToEdit.WorkNotCompletedDescription, 
                                   WorkForeman=ConditionToEdit.WorkForeman,
                                   WorkForemanSignoffIndicator=ConditionToEdit.WorkForemanSignoffIndicator, 
                                   WorkForemanSignoffDateTime=ConditionToEdit.WorkForemanSignoffDateTime,
                                   ReviewIndicator=ConditionToEdit.ReviewIndicator, 
                                   ReviewAdditionalAttentionNeededIndicator=ConditionToEdit.ReviewAdditionalAttentionNeededIndicator,
                                   ReviewComments=ConditionToEdit.ReviewComments, 
                                   ReviewUserName=ConditionToEdit.ReviewUserName, 
                                   ReviewDateTime=ConditionToEdit.ReviewDateTime,
                                   DeletedIndicator=DeletedIndicator, 
                                   LastModifyDateTime=ConditionToEdit.LastModifyDateTime, 
                                   LastModifyUserName=ConditionToEdit.LastModifyUserName,
                                   ArchivedIndicator=ConditionToEdit.ArchivedIndicator, 
                                   ArchivedUserName=ConditionToEdit.ArchivedUserName, 
                                   ArchivedDateTime=ConditionToEdit.ArchivedDateTime, Objectid=Objectid, 
                                   ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                                   ConditionDepartmentid=ConditionDepartmentid,
                                   PoleConditionStatus=PoleConditionStatus, GuyAnchorConditionStatus=GuyAnchorConditionStatus,
                                   InsulatorConditionStatus=InsulatorConditionStatus, ConductorConditionStatus=ConductorConditionStatus,
                                   RightOfWayConditionStatus=RightOfWayConditionStatus, PadMountConditionStatus=PadMountConditionStatus,
                                   VaultConditionStatus=VaultConditionStatus, RiserCableConditionStatus=RiserCableConditionStatus,
                                   OutdoorLightMapNumber=OutdoorLightMapNumber,
                                   OutdoorLightMeterNumber=OutdoorLightMeterNumber,
                                   OutdoorLightMeterMapNumber=OutdoorLightMeterMapNumber,
                                   OutdoorLightIdleIndicator=OutdoorLightIdleIndicator,
                                   OutdoorLightCustomerOwnsPoleIndicator=OutdoorLightCustomerOwnsPoleIndicator,
                                   OutdoorLightCustomerOwnsLightIndicator=OutdoorLightCustomerOwnsLightIndicator,
                                   OutdoorLightRateid=OutdoorLightRateid,
                                   OutdoorLightProblemCodeid=OutdoorLightProblemCodeid,
                                   OutdoorLightAdditionalBillingPoleCount = OutdoorLightAdditionalBillingPoleCount,
                                   OutdoorLightConsumerOwnedLightCount=OutdoorLightConsumerOwnedLightCount,
                                   OutdoorLightGISPhaseIndicator=ConditionToEdit.OutdoorLightGISPhaseIndicator, 
                                   OutdoorLightSendBackToBillingPhaseIndicator=ConditionToEdit.OutdoorLightSendBackToBillingPhaseIndicator)
            command.Process()
            if ConditionMemberDescription:
                command2 = Command()
                Conditionid, ConditionIndexWhenReverseSorted=ConditionToEdit.GetCommandidData()
                command2 = command2.Create(Name='CreateConditionMemberDescriptionHistory',
                                          CommandUserName = UserName,
                                          CommandCreateDateTime= datetime.datetime.now(),
                                          Conditionid = Conditionid, ConditionIndexWhenReverseSorted=ConditionIndexWhenReverseSorted,
                                          Description=ConditionMemberDescription)
                command2.Process()  


def PopulateOutdoorLightingForm(form, SelectionStation, NumberOfConditionsListedOnForm):
    if(SelectionStation):
        Conditions=list(Condition.objects.filter(PriorityOutdoorLightingConversionIndicator=True).exclude(
                                           DeletedIndicator=True).exclude(ArchivedIndicator=True).filter(
                                           Point__distance_lte=(SelectionStation.Point, 5)).order_by('id'))
        
    else:
        Conditions=[]
    StationAssembliesReport=[]
    SelectionStationAssemblies=Assembly.objects.filter(Station=SelectionStation)
    for i in SelectionStationAssemblies.filter(CompatibleUnit__LightIndicator=True):
        StationAssembliesReport.append(i.CompatibleUnit.Name + ', Map# ' + str(i.MapNumber) + ', Status: ' +  i.InstallStatus.Name)
    for i in SelectionStationAssemblies.filter(CompatibleUnit__PoleIndicator=True):
        StationAssembliesReport.append(i.CompatibleUnit.Name + ', Status: ' +  i.InstallStatus.Name)
    AssembliesAtSelectionStation='\n'.join(StationAssembliesReport)
    form.data['AssembliesAtSelectionStation'] = AssembliesAtSelectionStation
    for conditionFormNumber in range(0, NumberOfConditionsListedOnForm + 1):
        if conditionFormNumber < len(Conditions):
            Current=Conditions[conditionFormNumber]
            MeterMapNumber=Current.OutdoorLightMeterMapNumber
            LightCount=OutdoorLightConsumerOwnedLightCount.objects.filter(MeterMapNumber=MeterMapNumber)
            MemberDescription=ConditionMemberDescriptionHistory.objects.filter(Condition__id=Current.id).order_by('-CreateDateTime')
            if not LightCount.count():
                form.setData({'OutdoorLightCount' + str(conditionFormNumber):0})
            else:
                form.setData({'OutdoorLightConsumerOwnedLightCount' + str(conditionFormNumber):LightCount[0].LightCount})
            if not MemberDescription.count():
                form.setData({'ConditionMemberDescription' + str(conditionFormNumber):''})
            else:
                form.setData({'ConditionMemberDescription' + str(conditionFormNumber):MemberDescription[0].Description})
            form.setData({'UpdateIndicator' + str(conditionFormNumber):False})
            form.setData({'Conditionid' + str(conditionFormNumber):str(Current.id)})
            form.setData({'ConditionDepartment' + str(conditionFormNumber):Current.ConditionDepartment.id})
            #priority and general indicators
            form.data['PriorityImmediateIndicator' + str(conditionFormNumber)]=Current.PriorityImmediateIndicator
            form.data['PriorityASAPIndicator' + str(conditionFormNumber)]=Current.PriorityASAPIndicator
            form.data['PriorityRoutineIndicator' + str(conditionFormNumber)]=Current.PriorityRoutineIndicator
            form.data['PriorityEverythingFixedMaintenanceOnlyIndicator' + str(conditionFormNumber)]=Current.PriorityEverythingFixedMaintenanceOnlyIndicator
            form.data['PriorityEverythingOkInspectionOnlyIndicator' + str(conditionFormNumber)]=Current.PriorityEverythingOkInspectionOnlyIndicator
            form.data['PriorityVegetationNeedsAttentionIndicator' + str(conditionFormNumber)]=Current.PriorityVegetationNeedsAttentionIndicator
            form.data['PriorityOutdoorLightingConversionIndicator' + str(conditionFormNumber)]=Current.PriorityOutdoorLightingConversionIndicator
            form.data['NeedsRetirementIndicator' + str(conditionFormNumber)]=Current.NeedsRetirementIndicator
            #condition statuses
            form.setData({'PoleConditionStatus' + str(conditionFormNumber):Current.PoleConditionStatus.id})
            form.setData({'GuyAnchorConditionStatus' + str(conditionFormNumber):Current.GuyAnchorConditionStatus.id})
            form.setData({'InsulatorConditionStatus' + str(conditionFormNumber):Current.InsulatorConditionStatus.id})
            form.setData({'ConductorConditionStatus' + str(conditionFormNumber):Current.ConductorConditionStatus.id})
            form.setData({'RightOfWayConditionStatus' + str(conditionFormNumber):Current.RightOfWayConditionStatus.id})
            form.setData({'PadMountConditionStatus' + str(conditionFormNumber):Current.PadMountConditionStatus.id})
            form.setData({'VaultConditionStatus' + str(conditionFormNumber):Current.VaultConditionStatus.id})
            form.setData({'RiserCableConditionStatus' + str(conditionFormNumber):Current.RiserCableConditionStatus.id})
            #outdoor lighting
            form.data['OutdoorLightMapNumber' + str(conditionFormNumber)]=Current.OutdoorLightMapNumber
            form.data['OutdoorLightMeterNumber' + str(conditionFormNumber)]=Current.OutdoorLightMeterNumber
            form.data['OutdoorLightMeterMapNumber' + str(conditionFormNumber)]=Current.OutdoorLightMeterMapNumber
            form.data['OutdoorLightIdleIndicator' + str(conditionFormNumber)]=Current.OutdoorLightIdleIndicator
            form.data['OutdoorLightCustomerOwnsPoleIndicator' + str(conditionFormNumber)]=Current.OutdoorLightCustomerOwnsPoleIndicator
            form.data['OutdoorLightCustomerOwnsLightIndicator' + str(conditionFormNumber)]=Current.OutdoorLightCustomerOwnsLightIndicator
            if Current.OutdoorLightRate:
                form.setData({'OutdoorLightRate' + str(conditionFormNumber):Current.OutdoorLightRate.id})
            else:
                form.setData({'OutdoorLightRate' + str(conditionFormNumber): -1})
            if Current.OutdoorLightProblemCode:
                form.setData({'OutdoorLightProblemCode' + str(conditionFormNumber): Current.OutdoorLightProblemCode.id})
            else:
                form.setData({'OutdoorLightProblemCode' + str(conditionFormNumber): -1})
            form.data['OutdoorLightAdditionalBillingPoleCount' + str(conditionFormNumber)] = Current.OutdoorLightAdditionalBillingPoleCount
            form.data['PersonReporting' + str(conditionFormNumber)]=Current.PersonReporting
            form.data['DateTimeReported' + str(conditionFormNumber)]=Current.DateTimeReported
            form.data['ReceivedByOperationsIndicator' + str(conditionFormNumber)]=Current.ReceivedByOperationsIndicator 
            form.data['DateTimeReceivedByOperations' + str(conditionFormNumber)]=Current.DateTimeReceivedByOperations
            form.data['StationIdentifier' + str(conditionFormNumber)]=Current.StationIdentifier
            form.data['TagNumber' + str(conditionFormNumber)]=Current.TagNumber
            form.data['Description' + str(conditionFormNumber)]=Current.Description
            form.data['WorkOrderNumber' + str(conditionFormNumber)]=Current.WorkOrderNumber
            form.data['WorkRemarks' + str(conditionFormNumber)]=Current.WorkRemarks
            form.data['WorkPerformedBy' + str(conditionFormNumber)]=Current.WorkPerformedBy
            form.data['WorkHours' + str(conditionFormNumber)]=Current.WorkHours
            form.data['WorkDate' + str(conditionFormNumber)]=Current.WorkDate
            form.data['WorkCompletedIndicator' + str(conditionFormNumber)]=Current.WorkCompletedIndicator
            form.data['WorkNotCompletedIndicator' + str(conditionFormNumber)]=Current.WorkNotCompletedIndicator
            form.data['WorkNotCompletedDescription' + str(conditionFormNumber)]=Current.WorkNotCompletedDescription
            form.data['WorkForeman' + str(conditionFormNumber)]=Current.WorkForeman
            form.data['WorkForemanSignoffIndicator' + str(conditionFormNumber)]=Current.WorkForemanSignoffIndicator
            form.data['WorkForemanSignoffDateTime' + str(conditionFormNumber)]=Current.WorkForemanSignoffDateTime
            form.data['ReviewIndicator' + str(conditionFormNumber)]=Current.ReviewIndicator
            form.data['ReviewAdditionalAttentionNeededIndicator' + str(conditionFormNumber)]=Current.ReviewAdditionalAttentionNeededIndicator
            form.data['ReviewComments' + str(conditionFormNumber)]=Current.ReviewComments
            form.data['ReviewUserName' + str(conditionFormNumber)]=Current.ReviewUserName
            form.data['ReviewDateTime' + str(conditionFormNumber)]=Current.ReviewDateTime
            form.data['DeletedIndicator'+ str(conditionFormNumber)]=Current.DeletedIndicator
            form.data['CreateDateTime'+ str(conditionFormNumber)]=Current.CreateDateTime
            form.data['CreateUserName'+ str(conditionFormNumber)]=Current.CreateUserName
            form.data['LastModifyDateTime'+ str(conditionFormNumber)]=Current.LastModifyDateTime
            form.data['LastModifyUserName'+ str(conditionFormNumber)]=Current.LastModifyUserName
            if Current.OutdoorLightBillingWorkStartedIndicator and not Current.OutdoorLightGISPhaseIndicator:
                form.data['OutdoorLightBillingWorkStartedNotificationString' + str(conditionFormNumber)]='BILLING ONLY'
            else:
                form.data['OutdoorLightBillingWorkStartedNotificationString' + str(conditionFormNumber)]=''
        else:
            form.data['UpdateIndicator' + str(conditionFormNumber)]=False
            form.data['Conditionid' + str(conditionFormNumber)]='New'
            form.data['ConditionDepartment' + str(conditionFormNumber)]=None
            #priority indicators
            form.data['PriorityImmediateIndicator' + str(conditionFormNumber)]=False
            form.data['PriorityASAPIndicator' + str(conditionFormNumber)]=False
            form.data['PriorityRoutineIndicator' + str(conditionFormNumber)]=False
            form.data['PriorityEverythingFixedMaintenanceOnlyIndicator' + str(conditionFormNumber)]=False
            form.data['PriorityEverythingOkInspectionOnlyIndicator' + str(conditionFormNumber)]=False
            form.data['PriorityVegetationNeedsAttentionIndicator' + str(conditionFormNumber)]=False
            form.data['PriorityOutdoorLightingConversionIndicator' + str(conditionFormNumber)]=False
            form.data['NeedsRetirementIndicator' + str(conditionFormNumber)]=False
            #condition statuses
            form.data['PoleConditionStatus' + str(conditionFormNumber)]=None
            form.data['GuyAnchorConditionStatus' + str(conditionFormNumber)]=None
            form.data['InsulatorConditionStatus' + str(conditionFormNumber)]=None
            form.data['ConductorConditionStatus' + str(conditionFormNumber)]=None
            form.data['RightOfWayConditionStatus' + str(conditionFormNumber)]=None
            form.data['PadMountConditionStatus' + str(conditionFormNumber)]=None
            form.data['VaultConditionStatus' + str(conditionFormNumber)]=None
            form.data['RiserCableConditionStatus' + str(conditionFormNumber)]=None
            #outdoor lighting
            form.data['OutdoorLightMapNumber' + str(conditionFormNumber)]=''
            form.data['OutdoorLightMeterNumber' + str(conditionFormNumber)]=''
            form.data['OutdoorLightMeterMapNumber' + str(conditionFormNumber)]=''
            form.data['OutdoorLightIdleIndicator' + str(conditionFormNumber)]=False
            form.data['OutdoorLightCustomerOwnsPoleIndicator' + str(conditionFormNumber)]=False
            form.data['OutdoorLightCustomerOwnsLightIndicator' + str(conditionFormNumber)]=False
            form.setData({'OutdoorLightRate' + str(conditionFormNumber): -1})
            form.setData({'OutdoorLightProblemCode' + str(conditionFormNumber): -1})
            form.data['OutdoorLightAdditionalBillingPoleCount' + str(conditionFormNumber)] = ''
            form.data['OutdoorLightConsumerOwnedLightCount' + str(conditionFormNumber)]=''
            form.data['ConditionMemberDescription' + str(conditionFormNumber)]=''
            form.data['PersonReporting' + str(conditionFormNumber)]=''
            form.data['DateTimeReported' + str(conditionFormNumber)]=''
            form.data['ReceivedByOperationsIndicator' + str(conditionFormNumber)]=False 
            form.data['DateTimeReceivedByOperations' + str(conditionFormNumber)]=''
            form.data['StationIdentifier' + str(conditionFormNumber)]=''
            form.data['TagNumber' + str(conditionFormNumber)]=''
            form.data['Description' + str(conditionFormNumber)]=''
            form.data['WorkOrderNumber' + str(conditionFormNumber)]=''
            form.data['WorkRemarks' + str(conditionFormNumber)]=''
            form.data['WorkPerformedBy' + str(conditionFormNumber)]=''
            form.data['WorkHours' + str(conditionFormNumber)]=''
            form.data['WorkDate' + str(conditionFormNumber)]=''
            form.data['WorkCompletedIndicator' + str(conditionFormNumber)]=False
            form.data['WorkNotCompletedIndicator' + str(conditionFormNumber)]=False
            form.data['WorkNotCompletedDescription' + str(conditionFormNumber)]=''
            form.data['WorkForeman' + str(conditionFormNumber)]=''
            form.data['WorkForemanSignoffIndicator' + str(conditionFormNumber)]=False
            form.data['WorkForemanSignoffDateTime' + str(conditionFormNumber)]=''
            form.data['ReviewIndicator' + str(conditionFormNumber)]=False
            form.data['ReviewAdditionalAttentionNeededIndicator' + str(conditionFormNumber)]=False
            form.data['ReviewComments' + str(conditionFormNumber)]=''
            form.data['ReviewUserName' + str(conditionFormNumber)]=''
            form.data['ReviewDateTime' + str(conditionFormNumber)]=''
            form.data['DeletedIndicator'+ str(conditionFormNumber)]=False
            form.data['CreateDateTime'+ str(conditionFormNumber)]=''
            form.data['CreateUserName'+ str(conditionFormNumber)]=''
            form.data['LastModifyDateTime'+ str(conditionFormNumber)]=''
            form.data['LastModifyUserName'+ str(conditionFormNumber)]=''
            form.data['OutdoorLightBillingWorkStartedNotificationString' + str(conditionFormNumber)]=''


def BuildOutdoorLightingSendToBillingForm(SpecialBuildFormDataDict):
    Dict={}
    try:
        NumberOfConditionsListedOnForm=SpecialBuildFormDataDict['NumberOfConditionsListedOnForm']
    except:
        NumberOfConditionsListedOnForm=0
    OutdoorLightRateChoices=[]
    OutdoorLightRateChoices.append(['-1', 'None'])
    OutdoorLightRates=OutdoorLightRate.objects.all().order_by('id')
    for i in OutdoorLightRates:
        OutdoorLightRateChoices.append([i.id, str(i)])
    for i in range(0, NumberOfConditionsListedOnForm):
        Dict['UpdateIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['SendToBillingIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['TagNumber' + str(i)]=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['MapNumber' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
        Dict['MeterNumber' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
        Dict['MeterMapNumber' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
        Dict['IdleIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['NeedsRetirementIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['OutdoorLightRate' + str(i)] = forms.ChoiceField(OutdoorLightRateChoices, required=False)
        Dict['OutdoorLightAdditionalBillingPoleCount' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'6'}))
        Dict['CustomerOwnsPoleIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['CustomerOwnsLightIndicator' + str(i)] = forms.BooleanField(required=False)
        Dict['CircuitNumber' + str(i)] = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3, 'cols':40, 'READONLY': 'True'}))
        Dict['ConsumerOwnedLightCount' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'10'}))
        Dict['Conditionid' + str(i)] = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
        Dict['ConditionDepartment' + str(i)]=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'5'}))
        Dict['ConditionDescription' + str(i)]=forms.CharField(required=False, widget=forms.Textarea(attrs={'rows':3, 'cols':40}))
    return Dict

def GetCounty(station):
    try:
        county=County.objects.filter(Border__contains=station.Point)[0]
        return county.Name
    except:
        return 'Unknown'

def ProcessOutdoorLightingSendToBillingFormEntry(form, conditionFormNumber, UserName):
    UpdateIndicator=COOPGIS_FormMisc.FormGetBoolean(form, 'UpdateIndicator' + str(conditionFormNumber))
    Conditionid=COOPGIS_FormMisc.FormGetString(form, 'Conditionid' + str(conditionFormNumber))
    if (not UpdateIndicator) or (not Conditionid):
        return
    ConditionToEdit = Condition.objects.filter(id=Conditionid)[0]
    SendToBillingIndicator = COOPGIS_FormMisc.FormGetBoolean(form, 'SendToBillingIndicator'+ str(conditionFormNumber))
    TagNumber = COOPGIS_FormMisc.FormGetInteger(form, 'TagNumber'+ str(conditionFormNumber))
    MapNumber = COOPGIS_FormMisc.FormGetInteger(form, 'MapNumber' + str(conditionFormNumber))
    MeterNumber = COOPGIS_FormMisc.FormGetInteger(form, 'MeterNumber' + str(conditionFormNumber))
    MeterMapNumber = COOPGIS_FormMisc.FormGetInteger(form, 'MeterMapNumber' + str(conditionFormNumber))
    IdleIndicator = COOPGIS_FormMisc.FormGetBoolean(form, 'IdleIndicator'+ str(conditionFormNumber))
    NeedsRetirementIndicator = COOPGIS_FormMisc.FormGetBoolean(form, 'NeedsRetirementIndicator' + str(conditionFormNumber))
    OutdoorLightRateid = COOPGIS_FormMisc.FormGetInteger(form, 'OutdoorLightRate' + str(conditionFormNumber))
    OutdoorLightAdditionalBillingPoleCount = COOPGIS_FormMisc.FormGetInteger(form, 'OutdoorLightAdditionalBillingPoleCount' + str(conditionFormNumber))
    CustomerOwnsPoleIndicator = COOPGIS_FormMisc.FormGetBoolean(form, 'CustomerOwnsPoleIndicator' + str(conditionFormNumber))
    CustomerOwnsLightIndicator = COOPGIS_FormMisc.FormGetBoolean(form, 'CustomerOwnsLightIndicator' + str(conditionFormNumber))
    ConsumerOwnedLightCount = COOPGIS_FormMisc.FormGetInteger(form, 'ConsumerOwnedLightCount' + str(conditionFormNumber))
    ConditionMemberDescription = COOPGIS_FormMisc.FormGetString(form, 'ConditionDescription' + str(conditionFormNumber))
    if SendToBillingIndicator:
        OutdoorLightGISPhaseIndicator=False
    else:
        OutdoorLightGISPhaseIndicator = ConditionToEdit.OutdoorLightGISPhaseIndicator
        
    """
    Users can edit conditions that are marked as assigned to the GIS then/or attach notes, 
    then/or send to COOPIP for the Billing department to process.  Conditions can bounce back and forth as many times as needed.
    """
    Objectid, ObjectIndexWhenReverseSorted=ConditionToEdit.GetCommandidData()
    #START Condition command
    if(ConditionToEdit.OutdoorLightProblemCode):
        outdoorLightProblemCodeid = ConditionToEdit.OutdoorLightProblemCode.id
    else:
        outdoorLightProblemCodeid = -1
    command=Command()
    command=command.Create(Name='EditCondition', 
                             Objectid=Objectid, 
                             ObjectIndexWhenReverseSorted=ObjectIndexWhenReverseSorted,
                             PriorityImmediateIndicator=ConditionToEdit.PriorityImmediateIndicator,
                             PriorityASAPIndicator=ConditionToEdit.PriorityASAPIndicator, 
                             PriorityRoutineIndicator=ConditionToEdit.PriorityRoutineIndicator,
                             PriorityEverythingFixedMaintenanceOnlyIndicator=ConditionToEdit.PriorityEverythingFixedMaintenanceOnlyIndicator,
                             PriorityEverythingOkInspectionOnlyIndicator=ConditionToEdit.PriorityEverythingOkInspectionOnlyIndicator,
                             PriorityVegetationNeedsAttentionIndicator=ConditionToEdit.PriorityVegetationNeedsAttentionIndicator,
                             PriorityOutdoorLightingConversionIndicator=ConditionToEdit.PriorityOutdoorLightingConversionIndicator,
                             PersonReporting=ConditionToEdit.PersonReporting, 
                             DateTimeReported=ConditionToEdit.DateTimeReported, 
                             ReceivedByOperationsIndicator=ConditionToEdit.ReceivedByOperationsIndicator, 
                             DateTimeReceivedByOperations=ConditionToEdit.DateTimeReceivedByOperations, 
                             StationIdentifier=ConditionToEdit.StationIdentifier,
                             TagNumber=TagNumber,
                             Point=ConditionToEdit.Point,
                             Description=ConditionToEdit.Description, 
                             WorkOrderNumber=ConditionToEdit.WorkOrderNumber,
                             WorkRemarks=ConditionToEdit.WorkRemarks,
                             WorkPerformedBy=ConditionToEdit.WorkPerformedBy, 
                             HoursWorkedQuantity=ConditionToEdit.WorkHours, 
                             WorkDate=ConditionToEdit.WorkDate, 
                             WorkCompletedIndicator=ConditionToEdit.WorkCompletedIndicator,
                             WorkNotCompletedIndicator=ConditionToEdit.WorkNotCompletedIndicator,
                             WorkNotCompletedDescription=ConditionToEdit.WorkNotCompletedDescription,
                             WorkForeman=ConditionToEdit.WorkForeman,
                             WorkForemanSignoffIndicator=ConditionToEdit.WorkForemanSignoffIndicator,
                             WorkForemanSignoffDateTime=ConditionToEdit.WorkForemanSignoffDateTime,
                             ReviewIndicator=ConditionToEdit.ReviewIndicator, 
                             ReviewAdditionalAttentionNeededIndicator=ConditionToEdit.ReviewAdditionalAttentionNeededIndicator,
                             ReviewComments=ConditionToEdit.ReviewComments, 
                             ReviewUserName=ConditionToEdit.ReviewUserName, 
                             ReviewDateTime=ConditionToEdit.ReviewDateTime,
                             DeletedIndicator=ConditionToEdit.DeletedIndicator, 
                             CommandUserName=UserName,
                             LastModifyDateTime=ConditionToEdit.LastModifyDateTime, 
                             LastModifyUserName=ConditionToEdit.LastModifyUserName,
                             ArchivedIndicator=ConditionToEdit.ArchivedIndicator, 
                             ArchivedUserName=ConditionToEdit.ArchivedUserName, 
                             ArchivedDateTime=ConditionToEdit.ArchivedDateTime, 
                             ConditionDepartmentid=ConditionToEdit.ConditionDepartment.id,
                             PoleConditionStatus=ConditionToEdit.PoleConditionStatus.id, 
                             GuyAnchorConditionStatus=ConditionToEdit.GuyAnchorConditionStatus.id,
                             InsulatorConditionStatus=ConditionToEdit.InsulatorConditionStatus.id,
                             ConductorConditionStatus=ConditionToEdit.ConductorConditionStatus.id,
                             RightOfWayConditionStatus=ConditionToEdit.RightOfWayConditionStatus.id, 
                             PadMountConditionStatus=ConditionToEdit.PadMountConditionStatus.id,
                             VaultConditionStatus=ConditionToEdit.VaultConditionStatus.id, 
                             RiserCableConditionStatus=ConditionToEdit.RiserCableConditionStatus.id,
                             OutdoorLightMapNumber=MapNumber,
                             OutdoorLightMeterNumber=MeterNumber,
                             OutdoorLightMeterMapNumber=MeterMapNumber,
                             OutdoorLightIdleIndicator=IdleIndicator,
                             OutdoorLightCustomerOwnsPoleIndicator=CustomerOwnsPoleIndicator,
                             OutdoorLightCustomerOwnsLightIndicator=CustomerOwnsLightIndicator,
                             OutdoorLightRateid=OutdoorLightRateid,
                             OutdoorLightProblemCodeid=outdoorLightProblemCodeid,
                             OutdoorLightAdditionalBillingPoleCount=OutdoorLightAdditionalBillingPoleCount,
                             OutdoorLightConsumerOwnedLightCount=ConsumerOwnedLightCount,
                             NeedsRetirementIndicator=NeedsRetirementIndicator,
                             OutdoorLightGISPhaseIndicator = OutdoorLightGISPhaseIndicator,
                             OutdoorLightSendBackToBillingPhaseIndicator = SendToBillingIndicator)
    command.Process()
    if not ConditionMemberDescription:
        return
    RecentDescriptions = ConditionMemberDescriptionHistory.objects.filter(Condition__id=Conditionid).order_by('-CreateDateTime')
    if not RecentDescriptions.count():
        command = Command()
        Conditionid, ConditionIndexWhenReverseSorted=ConditionToEdit.GetCommandidData()
        command = command.Create(Name='CreateConditionMemberDescriptionHistory',
                                   CommandUserName = UserName,
                                   CommandCreateDateTime= datetime.datetime.now(),
                                   Conditionid = Conditionid, ConditionIndexWhenReverseSorted=ConditionIndexWhenReverseSorted,
                                   Description=ConditionMemberDescription)
        command.Process()  
    else:
        RecentDescription = RecentDescriptions[0]
        if RecentDescription.Description == ConditionMemberDescription:
            return
        command = Command()
        Conditionid, ConditionIndexWhenReverseSorted=ConditionToEdit.GetCommandidData()
        command = command.Create(Name='CreateConditionMemberDescriptionHistory',
                                   CommandUserName = UserName,
                                   CommandCreateDateTime= datetime.datetime.now(),
                                   Conditionid = Conditionid, ConditionIndexWhenReverseSorted=ConditionIndexWhenReverseSorted,
                                   Description=ConditionMemberDescription)
        command.Process()  

def PopulateOutdoorLightingSendToBillingForm(form, Conditions):
    NumberOfConditionsListedOnForm=len(Conditions)
    for conditionFormNumber in range(0, NumberOfConditionsListedOnForm):
        Current=Conditions[conditionFormNumber]
        LightCount=OutdoorLightConsumerOwnedLightCount.objects.filter(MeterMapNumber=Current.OutdoorLightMeterMapNumber)
        if not LightCount.count():
            form.setData({'OutdoorLightCount' + str(conditionFormNumber):0})
        else:
            form.setData({'OutdoorLightConsumerOwnedLightCount' + str(conditionFormNumber):LightCount[0].LightCount})
        form.setData({'UpdateIndicator' + str(conditionFormNumber):False})
        form.setData({'SendToBillingIndicator' + str(conditionFormNumber):False})
        form.data['Conditionid' + str(conditionFormNumber)]=str(Current.id)
        form.data['ConditionDepartment' + str(conditionFormNumber)]=str(Current.ConditionDepartment.id)
        form.data['TagNumber' + str(conditionFormNumber)]=Current.TagNumber
        form.data['MapNumber' + str(conditionFormNumber)] = Current.OutdoorLightMapNumber
        form.data['MeterNumber' + str(conditionFormNumber)] = Current.OutdoorLightMeterNumber
        form.data['MeterMapNumber' + str(conditionFormNumber)] = Current.OutdoorLightMeterMapNumber
        form.setData({'IdleIndicator' + str(conditionFormNumber):Current.OutdoorLightIdleIndicator})
        form.setData({'NeedsRetirementIndicator' + str(conditionFormNumber):Current.NeedsRetirementIndicator})
        form.setData({'CustomerOwnsPoleIndicator' + str(conditionFormNumber):Current.OutdoorLightCustomerOwnsPoleIndicator})
        form.setData({'CustomerOwnsLightIndicator' + str(conditionFormNumber):Current.OutdoorLightCustomerOwnsLightIndicator})
        if Current.OutdoorLightRate:
            form.setData({'OutdoorLightRate' + str(conditionFormNumber):Current.OutdoorLightRate.id})
        else:
            form.setData({'OutdoorLightRate' + str(conditionFormNumber): -1})
        form.setData({'OutdoorLightAdditionalBillingPoleCount' + str(conditionFormNumber):Current.OutdoorLightAdditionalBillingPoleCount})
        form.data['ConditionDescription' + str(conditionFormNumber)]=''
    return form
